Stores the rank ( depth ) of each node
int [ ] rank = new int [ n * m ] ; Arrays . fill ( rank , 1 ) ; boolean [ ] grid = new boolean [ n * m ] ; for ( int i = 0 ; i < query . length ; i ++ ) { int x = query [ i ] [ 0 ] ; int y = query [ i ] [ 1 ] ;