Find if a 2 | Javascript program to Find a 2 - D array is completely traversed or not by following the cell values ; Cell class constructor ; function which tells all cells are visited or not ; starting cell values ; if we get null before the end of loop then returns false . Because it means we didn 't traverse all the cells ; If found cycle then return false ; Update startx and starty values to next cell values ; finally if we reach our goal then returns true ; Driver program to test above function
class Cell { constructor ( x , y ) { this . x = x ; this . y = y ; } } function isAllCellTraversed ( grid ) { let visited = new Array ( grid . length ) ; for ( let i = 0 ; i < visited . length ; i ++ ) { visited [ i ] = new Array ( grid [ 0 ] . length ) ; } let total = grid . length * grid [ 0 ] . length ; let startx = grid [ 0 ] [ 0 ] . x ; let starty = grid [ 0 ] [ 0 ] . y ; for ( let i = 0 ; i < total - 2 ; i ++ ) { if ( grid [ startx ] [ starty ] == null ) return false ; if ( visited [ startx ] [ starty ] == true ) return false ; visited [ startx ] [ starty ] = true ; let x = grid [ startx ] [ starty ] . x ; let y = grid [ startx ] [ starty ] . y ; startx = x ; starty = y ; } if ( grid [ startx ] [ starty ] == null ) return true ; return false ; } let cell = new Array ( 3 ) ; for ( let i = 0 ; i < 3 ; i ++ ) { cell [ i ] = new Array ( 2 ) ; } cell [ 0 ] [ 0 ] = new Cell ( 0 , 1 ) ; cell [ 0 ] [ 1 ] = new Cell ( 2 , 0 ) ; cell [ 1 ] [ 0 ] = null ; cell [ 1 ] [ 1 ] = new Cell ( 1 , 0 ) ; cell [ 2 ] [ 0 ] = new Cell ( 2 , 1 ) ; cell [ 2 ] [ 1 ] = new Cell ( 1 , 1 ) ; document . write ( isAllCellTraversed ( cell ) ) ;