To keep track of rows and columns having 1
HashSet < int > rows = new HashSet < int > ( ) ; HashSet < int > cols = new HashSet < int > ( ) ; 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 ) ; } } }