题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.*; public static void main(String[] args) { public static ArrayList<Integer> list = new ArrayList<>(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = sc.nextInt(); } } find(0, 0, arr); for (int i = 0; i < list.size(); i += 2) { System.out.println("(" + list.get(i) + "," + list.get(i + 1) + ")"); } } public static void find(int x, int y, int[][] arr) { //越界 if (x < 0 || x >= arr.length || y < 0 || y >= arr[0].length) { return; } //撞墙 if (arr[x][y] == 1) { return; } //终止条件 if (x == arr.length - 1 && y == arr[0].length - 1) { list.add(x); list.add(y); return; } arr[x][y] = 1; list.add(x); list.add(y); find(x + 1, y, arr); find(x, y + 1, arr); find(x - 1, y, arr); find(x, y - 1, arr); if (list.size() > 0 && (list.get(list.size() - 2) == x && list.get(list.size() - 1) == y)) { // 如果当前位置是路径中的最后一个位置,说明已经回溯到起点,需要移除当前位置和上一个位置的坐标 list.remove(list.size() - 1); // 回溯,移除当前位置的坐标 list.remove(list.size() - 1); // 回溯,移除上一个位置的坐标 } else { // 恢复当前位置的值,继续回溯其他路径 arr[x][y] = 0; // 恢复当前位置的值 } }
}