在采访中询问了这个问题。给定网格4X4,你给出一些任意点,假设点(2,2)(索引从0开始),从你想要开始,从任何路径打印,你可以退出网格。您可以移动 LEFT , RIGHT , TOP , BOTTON 。在下面的网格中,1 - 代表块,0:你可以移动。
1 0 1 1
0 0 0 0
1 1 0 1
1 1 1 1
上面网格的退出路径是,(2,2)=> (1,2)=> (1,1)=> (0,1)
我试图通过DFS解决这个问题(下面),但是我找不到解决方案如何打印任何一个Path,下面是打印所有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;
}
}
答案 0 :(得分:3)
您需要另一个实用程序功能来检查当前点是否即将退出。
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);
}
现在在while循环中,当遇到退出点时,打印并退出循环。您还需要更正isValidMove
和printTraversal
功能。
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;
}
// For other 3 sides
// .............
}
}