To keep track of rows and columns having 1
rows = set ( ) NEW_LINE cols = set ( ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if mat [ i ] [ j ] : NEW_LINE INDENT rows . add ( i ) NEW_LINE cols . add ( j ) NEW_LINE DEDENT DEDENT DEDENT