To keep track of rows and columns having 1
set < int > rows ; set < int > cols ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( mat [ i ] [ j ] ) { rows . insert ( i ) ; cols . insert ( j ) ; } } }