java - Print any exit path, from any arbitrary point to outside grid? -
this question asked in interview. given grid 4x4, give arbitrary point suppose point (2,2)(index starting 0), there want start, print 1 path there can exit grid. allow move left, right, top, botton. in following grid, 1 - represents block, 0 : can move.
1 0 1 1
0 0 0 0
1 1 0 1
1 1 1 1
exit path above grid is, (2, 2)=> (1, 2) => (1, 1) => (0, 1)
i tried solve problem (below), through dfs, not able find solution how print 1 of path, following printing path, want print path.
public boolean isvalidmove(point point){ if(array[point.getx()][point.gety()]==0){ return true; } return false; } public void printtraversal(int [][] array, int m, int n, point start){ boolean [] visited = boolean[m*n]; arrays.fill(visited, false); int index = start.getx()*m+ start.gety(); boolean[index] = true; stack<point> stack = new stack<point>(); stack.push(start); while(!stack.isempty()){ point point = stack.pop(); system.out.println(point.getx()+", "+ point.gety()); int x = point.getx(); int y = point.gety(); if(isvalidmove(x-1, y-1)){ stack.push(new point(x-1, y-1)); } if(isvalidmove(x-1, y)){ stack.push(new point(x-1, y)); } if(isvalidmove(x, y-1)){ stack.push(new point(x, y-1)); } if(isvalidmove(x+1, y+1)){ stack.push(new point(x+1, y+1)); } } } class point{ private int x; private int y; public point(int x, int y){ this.x = x; this.y = y; } public int getx(){ return this.x; } public int gety(){ return this.y; } }
you need utility function check if current point exit or not.
public boolean isexit(point point, int m, int n) { int x = point.getx(); int y = point.gety(); return (x == 0 || y == 0 || x == m - 1 || y == n - 1); }
and in while loop, when encounter exit point, print , exit loop. need correct isvalidmove
, printtraversal
function bit.
public boolean isvalidmove(point point, int m, int n) { int x = point.getx(); int y = point.gety(); if(x >= 0 && y >= 0 && x < m && y < n && array[x][y] == 0 ) { return true; } return false; } private int getindx(point p, int m) { return p.getx() * m + p.gety(); } public void printtraversal(int [][] array, int m, int n, point start){ if(m == 0 || n == 0) { return; } boolean [] visited = boolean[m * n]; arrays.fill(visited, false); visited[ getindx(start, m) ] = true; stack<point> stack = new stack<point>(); stack.push(start); while(!stack.isempty()) { point point = stack.pop(); system.out.println(point.getx()+", "+ point.gety()); if(isexit(point, m, n)) break; int x = point.getx(); int y = point.gety(); point neigh = new point(x-1, y-1); if(isvalidmove(x-1, y-1, m, n) && !visited[ getindx(neigh, m) ]){ stack.push( neigh ); visited[ getindx(neigh, m) ] = true; } // other 3 sides // ............. } }
Comments
Post a Comment