Java用栈来求解走迷宫问题
时间: 2023-06-14 13:06:52 浏览: 48
走迷宫问题可以使用回溯算法来解决,栈可以帮助我们记录路径信息以及回溯时的状态信息。以下是使用栈来求解走迷宫问题的Java代码:
```java
import java.util.Stack;
public class MazeSolver {
private int[][] maze;
private boolean[][] visited;
private Stack<int[]> stack;
public MazeSolver(int[][] maze) {
this.maze = maze;
this.visited = new boolean[maze.length][maze[0].length];
this.stack = new Stack<>();
}
public boolean solve(int startX, int startY, int endX, int endY) {
stack.push(new int[]{startX, startY});
while(!stack.isEmpty()) {
int[] current = stack.pop();
int x = current[0], y = current[1];
if(x < 0 || y < 0 || x >= maze.length || y >= maze[0].length || visited[x][y] || maze[x][y] == 1) {
continue;
}
visited[x][y] = true;
if(x == endX && y == endY) {
return true;
}
stack.push(new int[]{x - 1, y});
stack.push(new int[]{x + 1, y});
stack.push(new int[]{x, y - 1});
stack.push(new int[]{x, y + 1});
}
return false;
}
}
```
这段代码中,我们首先定义了一个`maze`数组来表示迷宫,以及一个`visited`数组来记录哪些位置已经被访问过。我们还定义了一个`stack`来存储路径信息。
在`solve`方法中,我们首先把起点压入栈中。然后,我们不断从栈中弹出一个位置,检查它是否可行。如果不可行,则跳过。否则,我们将这个位置标记为已访问,并检查它是否是终点。如果是终点,则返回`true`。否则,我们将它周围的四个方向都压入栈中。
如果栈为空,说明无法到达终点,返回`false`。