题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 // while (in.hasNextInt()) { // 注意 while 处理多个 case // int a = in.nextInt(); // int b = in.nextInt(); // System.out.println(a + b); // } int m = in.nextInt(); int n = in.nextInt(); int[][] table = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { table[i][j] = in.nextInt(); } } ArrayList<Node> path = new ArrayList<>(); dfs(table, 0, 0, path); for (int i = 0; i < path.size(); i++) { System.out.println("(" + path.get(i).x + "," + path.get(i).y + ")"); } } private static boolean dfs(int[][] table, int x, int y, List<Node> path) { path.add(new Node(x, y)); table[x][y] = 1; int m = table.length; int n = table[0].length; if (x == m - 1 && y == n - 1) { return true; } if (x + 1 < m && table[x + 1][y] == 0) { if (dfs(table, x + 1, y, path)) { return true; } } if (x - 1 >= 0 && table[x - 1][y] == 0) { if (dfs(table, x - 1, y, path)) { return true; } } if (y + 1 < n && table[x][y + 1] == 0) { if (dfs(table, x, y + 1, path)) { return true; } } if (y - 1 >= 0 && table[x][y - 1] == 0) { if (dfs(table, x, y - 1, path)) { return true; } } path.remove(path.size() - 1); return false; } } class Node { protected int x; protected int y; // protected Node father; protected Node (int x, int y) { this.x = x; this.y = y; // this.father = father; } }