queue to do BFS .
Queue < Integer > Q = new LinkedList < > ( ) ; distance . setElementAt ( 0 , u ) ; Q . add ( u ) ; visited . setElementAt ( true , u ) ; while ( ! Q . isEmpty ( ) ) { int x = Q . peek ( ) ; Q . poll ( ) ; for ( int i = 0 ; i < edges [ x ] . size ( ) ; i ++ ) { if ( visited . elementAt ( edges [ x ] . get ( i ) ) ) continue ;