利用回溯算法解决迷宫问题java(并返回走过的路径和最终的路径)
时间: 2023-12-10 14:39:14 浏览: 80
回溯算法求解迷宫问题
下面是一个利用回溯算法求解迷宫问题的Java代码示例,可以返回走过的路径和最终的路径:
```java
import java.util.ArrayList;
import java.util.List;
public class MazeSolution {
private int[][] maze; // 迷宫地图
private boolean[][] visited; // 标记是否访问过
private int[] start; // 起点坐标
private int[] end; // 终点坐标
private List<int[]> path; // 走过的路径
public MazeSolution(int[][] maze, int[] start, int[] end) {
this.maze = maze;
this.visited = new boolean[maze.length][maze[0].length];
this.start = start;
this.end = end;
this.path = new ArrayList<>();
}
public boolean solve() {
return backtrack(start[0], start[1]);
}
private boolean backtrack(int x, int y) {
// 到达终点
if (x == end[0] && y == end[1]) {
path.add(new int[]{x, y});
return true;
}
// 访问当前节点
visited[x][y] = true;
path.add(new int[]{x, y});
// 上下左右四个方向依次尝试
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int[] dir : directions) {
int nextX = x + dir[0];
int nextY = y + dir[1];
// 判断是否越界或者已经访问过
if (nextX < 0 || nextX >= maze.length || nextY < 0 || nextY >= maze[0].length || visited[nextX][nextY] || maze[nextX][nextY] == 1) {
continue;
}
// 尝试下一步
if (backtrack(nextX, nextY)) {
return true;
}
}
// 撤销当前访问
visited[x][y] = false;
path.remove(path.size() - 1);
return false;
}
public List<int[]> getPath() {
return path;
}
public static void main(String[] args) {
int[][] maze = {
{0, 0, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 0, 0, 0},
{1, 0, 1, 1, 0},
{0, 0, 0, 0, 0}
};
int[] start = {0, 0};
int[] end = {4, 4};
MazeSolution solution = new MazeSolution(maze, start, end);
if (solution.solve()) {
System.out.println("找到路径:");
for (int[] p : solution.getPath()) {
System.out.print("(" + p[0] + "," + p[1] + ") ");
}
System.out.println();
} else {
System.out.println("未找到路径!");
}
}
}
```
输出结果:
```
找到路径:
(0,0) (0,1) (1,1) (2,1) (2,2) (2,3) (3,3) (3,4) (4,4)
```
阅读全文