题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.Scanner; import java.util.Arrays; import java.util.List; import java.util.ArrayList; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] line = in.nextLine().split(" "); int xTotal = Integer.parseInt(line[0]); int yTotal = Integer.parseInt(line[1]); int[][] arrs = new int[xTotal][yTotal]; for (int i = 0 ; i < xTotal ; i++) { line = in.nextLine().split(" "); for (int j = 0; j < yTotal ; j++) { arrs[i][j] = Integer.parseInt(line[j]); } } int x = 0; int y = 0; List<String> path = new ArrayList<>(); //添加起始坐标 path.add("0,0"); //记录当前错误的坐标 String errStep = null; //循环直到(xTotal -1 ,yTotal -1) String endSep = (xTotal - 1) + "," + (yTotal - 1); while (!endSep.equals(x + "," + y)) { //寻找下一步 String step = findNext(arrs, x, y, path, xTotal, yTotal, errStep); if (null != step) { //找到下一步,记录路径 path.add(step); //坐标移动至下一步 String[] steps = step.split(","); x = Integer.parseInt(steps[0]); y = Integer.parseInt(steps[1]); } else { //记录当前错误的坐标 errStep = x + "," + y; //未找到下一步,退回一步 String preStep = path.get(path.size() - 2); path.remove(path.size() - 1); String[] preSteps = preStep.split(","); x = Integer.parseInt(preSteps[0]); y = Integer.parseInt(preSteps[1]); } } path.forEach(a -> System.out.println("(" + a + ")")); } public static String findNext(int[][] arrs, int x, int y, List<String> path, int xTotal, int yTotal, String errorStep) { //上 if (x - 1 >= 0 && arrs[x - 1][y] == 0) { String key = (x - 1) + "," + y; if (!path.contains(key) && !key.equals(errorStep)) { return key; } } //右 if (x + 1 < xTotal && arrs[x + 1][y] == 0) { String key = (x + 1) + "," + y; if (!path.contains(key) && !key.equals(errorStep)) { return key; } } //左 if (y - 1 >= 0 && arrs[x][y - 1] == 0) { String key = x + "," + (y - 1); if (!path.contains(key) && !key.equals(errorStep)) { return key; } } //下 if (y + 1 < yTotal && arrs[x][y + 1] == 0) { String key = x + "," + (y + 1); if (!path.contains(key) && !key.equals(errorStep)) { return key; } } return null; } }