题解 | #迷宫问题# dfs思路详解
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.*;
import java.lang.*;
/**
* 难点:
* 无思路,不知道走通和保存一路上的坐标路径如何结合起来。
* 题意说,只有一条路径符合要求,因此可使用DFS,多条可使用BFS
* 思路:
* 首先分三部分,输入,处理,输出
* 1、输入:就是构建迷宫map,很简单
* 2、输出:就是把这一路上的坐标输出去,于是就需要一个存储坐标的类Pos,还需要一个path来存储这些Pos
* 3、处理:dfs,其实就是回溯求path。
* 先把当前这个点加入path,然后变为1
* 终止条件:判断这个点是不是终点,如果是就结束(return true)
* 没到终点:接下来就是看上下左右哪个能走得通,都试试,一直dfs直到终点return true
* 回溯:如果前后左右都走不通,就删除这个点,回到0,返回false(告知此路不通)。
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int m = in.nextInt();
int n = in.nextInt();
// 构造迷宫
int[][] map = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
map[i][j] = in.nextInt();
}
}
// 路径存储的数组
List<Pos> path = new ArrayList<>();
// DFS搜索路径
dfs(map, 0, 0, path);
// 输出
for (Pos p : path) {
System.out.println("(" + p.x + "," + p.y + ")");
}
}
}
// 返回值 标记是否找到可通行的路径
public static boolean dfs(int[][] map, int x, int y, List<Pos> path) {
// 添加路径并标记已走
path.add(new Pos(x, y));
map[x][y] = 1;
// 结束标志
if (x == map.length - 1 && y == map[0].length - 1) {
return true;
}
// 向下能走时
if (x + 1 < map.length && map[x + 1][y] == 0) {
if (dfs(map, x + 1, y, path)) {
return true;
}
}
// 向上能走时
if (x - 1 >= 0 && map[x - 1][y] == 0) {
if (dfs(map, x - 1, y, path)) {
return true;
}
}
// 向左能走时
if (y - 1 >= 0 && map[x][y - 1] == 0) {
if (dfs(map, x, y - 1, path)) {
return true;
}
}
// 向右能走时
if (y + 1 < map[0].length && map[x][y + 1] == 0) {
if (dfs(map, x, y + 1, path)) {
return true;
}
}
// 回溯
path.remove(path.size() - 1);
map[x][y] = 0;
return false;
}
}
class Pos {
int x;
int y;
public Pos(int x, int y) {
this.x = x;
this.y = y;
}
}

