题解 | #迷宫问题#
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
递归
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
private static int n;
private static int m;
private static int[][] maze;
private static class Point {
int x;
int y;
Point(int x,int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
n = sc.nextInt();
m = sc.nextInt();
maze = new int[n][m];
for (int i = 0;i < n;i++) {
for (int j = 0;j < m;j++) {
maze[i][j] = sc.nextInt();
}
}
find(0,0,new ArrayList<>());
}
}
private static void find(int x,int y,List<Point> list) {
// 越界
if (x < 0 || y < 0 || x > n-1 || y > m-1) {
return;
}
// 终点
if (x == n-1 && y == m-1) {
List<Point> newList = new ArrayList<>(list);
newList.add(new Point(x,y));
for (Point point : newList) {
System.out.println(point);
}
return;
}
// 否则是0才继续往下走
if (maze[x][y] == 0) {
List<Point> newList = new ArrayList<>(list);
newList.add(new Point(x,y));
// 走过的点不能再走,防止无限递归
maze[x][y] = 1;
// 上下左右四个方向,不用判断往回走
find(x + 1,y,newList);
find(x - 1,y,newList);
find(x,y + 1,newList);
find(x,y - 1,newList);
}
return;
}
}