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 [ COUNT ] += 1 ; } else { mp . Add ( COUNT , 1 ) ; } } } } }