题解 | #走迷宫#
走迷宫
https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.ArrayDeque; import java.util.Deque; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] str1 = br.readLine().split(" "); int n = Integer.parseInt(str1[0]); int m = Integer.parseInt(str1[1]); boolean[][] array = new boolean[n + 1][m + 1]; String[] str2 = br.readLine().split(" "); int x1 = Integer.parseInt(str2[0]); int y1 = Integer.parseInt(str2[1]); int x2 = Integer.parseInt(str2[2]); int y2 = Integer.parseInt(str2[3]); for (int i = 1 ; i <= n; i++) { char[] chars = br.readLine().toCharArray(); for (int j = 1; j <= m; j++) { array[i][j] = chars[j-1] == '.' ? true : false; } } Deque<int[]> queue = new ArrayDeque<>(); //将起点加入队列并将array置为false queue.add(new int[] {x1, y1}); array[x1][y1] = false; //记录步数 int steps = 0; //图中每层未遍历的节点数 int remain = 1; while (!queue.isEmpty()) { //每个点下层节点的个数 int size = 0; while (remain > 0) { int[] position = queue.remove();//遍历 int x = position[0]; int y = position[1]; remain --; //对周围的四个方位分别进行可达探测,从而得到遍历后的节点的下层节点 if (y - 1 >= 1 && array[x][y - 1]) { //到达指定位置 if (x == x2 && y-1 == y2) { System.out.println(steps + 1); return; } queue.add(new int[] {x, y - 1}); array[x][y - 1] = false; size++; } if (y + 1 <= m && array[x][y + 1]) { if (x == x2 && y + 1 == y2) { System.out.println(steps + 1); return; } queue.add(new int[] {x, y + 1}); array[x][y + 1] = false; size++; } if (x - 1 >= 1 && array[x - 1][y]) { if (x - 1 == x2 && y == y2) { System.out.println(steps + 1); return; } queue.add(new int[] {x - 1, y}); array[x - 1][y] = false; size++; } if (x + 1 <= n && array[x + 1][y]) { if (x + 1 == x2 && y == y2) { System.out.println(steps + 1); return; } queue.add(new int[] {x + 1, y}); array[x + 1][y] = false; size++; } } remain = size; steps++; } System.out.println(-1); } }