text: To keep track of rows and columns having 1
code: Set < Integer > rows = new HashSet < Integer > ( ) ; Set < Integer > cols = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( mat [ i ] [ j ] > 0 ) ) { rows . add ( i ) ; cols . add ( j ) ; } } }