Find if a binary matrix exists with given row and column sums | 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
def matrix_exist ( row , column , r , c ) : NEW_LINE INDENT row_sum = 0 NEW_LINE column_sum = 0 NEW_LINE row_max = - 1 NEW_LINE column_max = - 1 NEW_LINE row_non_zero = 0 NEW_LINE column_non_zero = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT row_sum += row [ i ] NEW_LINE row_max = max ( row_max , row [ i ] ) NEW_LINE if ( row [ i ] ) : NEW_LINE INDENT row_non_zero = row_non_zero + 1 NEW_LINE DEDENT DEDENT for i in range ( c ) : NEW_LINE INDENT column_sum = column_sum + column [ i ] NEW_LINE column_max = max ( column_max , column [ i ] ) NEW_LINE if ( column [ i ] ) : NEW_LINE INDENT column_non_zero = column_non_zero + 1 NEW_LINE DEDENT DEDENT if ( ( row_sum != column_sum ) or ( row_max > column_non_zero ) or ( column_max > row_non_zero ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT row = [ 2 , 2 , 2 , 2 , 2 ] NEW_LINE column = [ 5 , 5 , 0 , 0 ] NEW_LINE r = len ( row ) NEW_LINE c = len ( column ) NEW_LINE if matrix_exist ( row , column , r , c ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT