题解 | #迷宫问题#
迷宫问题
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); int m = in.nextInt(); int n = in.nextInt(); int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { arr[i][j] = in.nextInt(); } } List<int[]> res = new ArrayList<>(); boolean[][] used = new boolean[m][n]; bfs(res, arr, used, 0, 0); // for (int[] step : res) { // System.out.println("(" + step[0] + "," + step[1] + ")"); // } } private static void bfs(List<int[]> res, int[][] arr, boolean[][] used, int row, int col) { if (!valid(arr, row, col)) { return; } if (row == arr.length - 1 && col == arr[0].length - 1) { res.add(new int[] {row, col}); for (int[] step : res) { System.out.println("(" + step[0] + "," + step[1] + ")"); } return; } if (used[row][col]) { return; } if (arr[row][col] == 0) { used[row][col] = true; res.add(new int[] {row, col}); bfs(res, arr, used, row + 1, col); bfs(res, arr, used, row - 1, col); bfs(res, arr, used, row, col + 1); bfs(res, arr, used, row, col - 1); res.remove(res.size() - 1); used[row][col] = false; } } private static boolean valid(int[][] arr, int row, int col) { if (row < 0 || row >= arr.length || col < 0 || col >= arr[0].length) { return false; } if (arr[row][col] == 1) { return false; } return true; } }