Find if a 2 | Java 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
import java . io . * ; class Cell { int x ; int y ; Cell ( int x , int y ) { this . x = x ; this . y = y ; } } public class MoveCellPerCellValue { public boolean isAllCellTraversed ( Cell grid [ ] [ ] ) { boolean [ ] [ ] visited = new boolean [ grid . length ] [ grid [ 0 ] . length ] ; int total = grid . length * grid [ 0 ] . length ; int startx = grid [ 0 ] [ 0 ] . x ; int starty = grid [ 0 ] [ 0 ] . y ; for ( int i = 0 ; i < total - 2 ; i ++ ) { if ( grid [ startx ] [ starty ] == null ) return false ; if ( visited [ startx ] [ starty ] == true ) return false ; visited [ startx ] [ starty ] = true ; int x = grid [ startx ] [ starty ] . x ; int y = grid [ startx ] [ starty ] . y ; startx = x ; starty = y ; } if ( grid [ startx ] [ starty ] == null ) return true ; return false ; } public static void main ( String args [ ] ) { Cell cell [ ] [ ] = new Cell [ 3 ] [ 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 ) ; MoveCellPerCellValue mcp = new MoveCellPerCellValue ( ) ; System . out . println ( mcp . isAllCellTraversed ( cell ) ) ; } }