Create an array isPresent and initialize all entries of it as false . The value of isPresent [ i , j ] is going to be true if s [ i , j ] is present in its row or column .
boolean [ ] [ ] isPresent = new boolean [ n ] [ m ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { isPresent [ i ] [ j ] = false ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) {