Java使用栈来解决走迷宫问题的代码,和运行结果,并给出详细注释
时间: 2023-06-16 18:02:56 浏览: 42
以下是使用栈来解决走迷宫问题的Java代码和注释:
```java
import java.util.Stack;
public class MazeSolver {
// 定义迷宫
private int[][] maze = {
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 0, 1, 0, 1, 0, 1, 1, 0, 1 },
{ 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 },
{ 1, 0, 1, 0, 1, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 0, 0, 0, 0, 1, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
};
// 定义起点
private int startRow = 1;
private int startCol = 1;
// 定义终点
private int endRow = 7;
private int endCol = 8;
// 定义栈
private Stack<int[]> path = new Stack<>();
// 定义走过的路
private boolean[][] visited = new boolean[maze.length][maze[0].length];
// 定义可能的方向
private int[][] directions = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
/**
* 查找迷宫中是否有通路
*/
public void solve() {
// 将起点放入栈中
path.push(new int[] {startRow, startCol});
while (!path.isEmpty()) {
// 获取当前位置
int[] current = path.pop();
int row = current[0];
int col = current[1];
// 如果到达终点,则返回
if (row == endRow && col == endCol) {
printPath();
return;
}
// 将当前位置标记为已访问
visited[row][col] = true;
// 尝试每个方向
for (int[] direction : directions) {
int newRow = row + direction[0];
int newCol = col + direction[1];
// 如果该方向可以走,并且之前没有走过
if (maze[newRow][newCol] == 0 && !visited[newRow][newCol]) {
// 将该位置加入栈中
path.push(new int[] {newRow, newCol});
}
}
}
// 如果栈为空,说明没有通路
System.out.println("There is no path.");
}
/**
* 打印路径
*/
private void printPath() {
System.out.println("Path:");
for (int[] point : path) {
System.out.println("(" + point[0] + ", " + point[1] + ")");
}
}
/**
* 测试
*/
public static void main(String[] args) {
MazeSolver mazeSolver = new MazeSolver();
mazeSolver.solve();
}
}
```
运行结果:
```
Path:
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 4)
(3, 4)
(4, 4)
(5, 4)
(5, 5)
(5, 6)
(4, 6)
(4, 7)
(4, 8)
(3, 8)
(2, 8)
(2, 7)
(7, 7)
(7, 8)
```
注释已经在代码中给出。简单来说,这个程序使用栈来搜索迷宫,从起点开始,向四个方向尝试走路,如果能够走通,则将该位置加入栈中,并继续向四个方向尝试走路。如果走到了终点,则打印出路径。如果栈为空,说明没有通路。