题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.ArrayList; import java.util.Scanner; //走迷宫 // 注意类名必须为 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 n = in.nextInt();//n行m列的数组 int m = in.nextInt(); int[][] map = new int[n + 2][m + 2]; //在数组外围一圈补1,代表墙壁 for (int j = 0; j < m + 2; j++) { map[0][j] = 1; map[n + 1][j] = 1; } for (int i = 1; i < n + 1; i++) { for (int j = 0; j < m + 2; j++) { if (j == 0 || j == m + 1) { map[i][j] = 1; } else { map[i][j] = in.nextInt(); } } } ArrayList<Point> way = new ArrayList<Point>(); fingWay(1, 1, map, way); for (int i = 0; i < way.size(); i++) { System.out.println(way.get(i)); } } in.close(); } //返回路线ArrayList public static boolean fingWay(int x, int y, int[][] map, ArrayList<Point> way) { map[x][y] = 1; way.add(new Point(x, y)); if (x == map.length - 2 && y == map[0].length - 2) { return true; } if (map[x][y + 1] == 0) {//right if (fingWay(x, y + 1, map, way)) { return true; } } if (map[x + 1][y] == 0) {//down if (fingWay(x + 1, y, map, way)) { return true; } } if (map[x][y - 1] == 0) {//left if (fingWay(x, y - 1, map, way)) { return true; } } if (map[x - 1][y] == 0) {//up if (fingWay(x - 1, y, map, way)) { return true; } } way.remove(way.size() - 1); map[x][y] = 0; return false; } public static class Point { private int x; private int y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "(" + (x - 1) + "," + (y - 1) + ")"; } } }