Go to the adjacent cells
for ( int k = 0 ; k < 4 ; k ++ ) { int newX = x + dx [ k ] ; int newY = y + dy [ k ] ; if ( is_valid ( newX , newY , matrix ) ) { q . add ( new pair ( newX , newY ) ) ; visited [ newX ] [ newY ] = 1 ; } } } if ( mp . containsKey ( COUNT ) ) { mp . put ( COUNT , mp . get ( COUNT ) + 1 ) ; } else { mp . put ( COUNT , 1 ) ; } } } } }