Find if a binary matrix exists with given row and column sums | C ++ implementation of the above approach ; Function to check if matrix exists ; Store sum of rowsums , max of row sum number of non zero row sums ; Store sum of column sums , max of column sum number of non zero column sums ; Check condition 1 , 2 , 3 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool matrix_exist ( int row [ ] , int column [ ] , int r , int c ) { int row_sum = 0 ; int column_sum = 0 ; int row_max = -1 ; int column_max = -1 ; int row_non_zero = 0 ; int column_non_zero = 0 ; for ( int i = 0 ; i < r ; i ++ ) { row_sum += row [ i ] ; row_max = max ( row_max , row [ i ] ) ; if ( row [ i ] ) row_non_zero ++ ; } for ( int i = 0 ; i < c ; i ++ ) { column_sum += column [ i ] ; column_max = max ( column_max , column [ i ] ) ; if ( column [ i ] ) column_non_zero ++ ; } if ( ( row_sum != column_sum ) || ( row_max > column_non_zero ) || ( column_max > row_non_zero ) ) return false ; return true ; } int main ( ) { int row [ ] = { 2 , 2 , 2 , 2 , 2 } ; int column [ ] = { 5 , 5 , 0 , 0 } ; int r = sizeof ( row ) / sizeof ( row [ 0 ] ) ; int c = sizeof ( column ) / sizeof ( column [ 0 ] ) ; if ( matrix_exist ( row , column , r , c ) ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; }