DFS+回溯轻松解决迷宫问题!最优雅最清楚的代码!!!
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
//BufferedReader in = new Bufferedreader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int m = in.nextInt();
int n = in.nextInt();
int[][] maze = new int[m][n];
for (int i = 0; i < m; i++) { //行
for (int j = 0; j < n; j++) {
//map记录整个迷宫
maze[i][j] = in.nextInt();
}
}
dfs5(maze, new int[] {0, 0}, new int[] {maze.length - 1, maze[0].length - 1},
list);
for (int[] arr : list) {
System.out.println("(" + arr[0] + "," + arr[1] + ")");
}
}
}
public static ArrayList<int[]> list = new ArrayList<>();
public static void dfs5(int[][]maze, int[] start, int[] des,
ArrayList<int[]> path) {
if (start[0] == des[0] && start[1] == des[1]) {
path.add(new int[] {maze.length - 1, maze[0].length - 1});
list = new ArrayList<>(path);
return;
}
int l = start[1] - 1;
int r = start[1] + 1;
int u = start[0] - 1;
int d = start[0] + 1;
maze[start[0]][start[1]] = -1;
path.add(new int[] {start[0], start[1]});
if (l >= 0 && maze[start[0]][l] == 0) {
dfs5(maze, new int[] {start[0], l}, des, path);
}
if (r < maze[0].length && maze[start[0]][r] == 0) {
dfs5(maze, new int[] {start[0], r}, des, path);
}
if (u >= 0 && maze[u][start[1]] == 0) {
dfs5(maze, new int[] {u, start[1]}, des, path);
}
if (d < maze.length && maze[d][start[1]] == 0) {
dfs5(maze, new int[] {d, start[1]}, des, path);
}
maze[start[0]][start[1]] = 0;
path.remove(path.size() - 1);
}
}
