题解 | #迷宫问题#
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] nm = scan.nextLine().split(" ");
int n = Integer.valueOf(nm[0]);
int m = Integer.valueOf(nm[1]);
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
String[] currRow = scan.nextLine().split(" ");
for (int j = 0; j < m; j++) {
matrix[i][j] = Integer.valueOf(currRow[j]);
}
}
ArrayList<int[]> ans = new ArrayList<>();
process(0, 0, n, m, ans, matrix);
for (int[] tmp : ans) {
System.out.println("(" + tmp[0] + "," + tmp[1] + ")");
}
}
public static boolean process(int cx, int cy, int n, int m, ArrayList<int[]> ans, int[][] matrix) {
if (cx < 0 || cx >= n || cy < 0 || cy >= m || matrix[cx][cy] == 1) {
return false;
}
if (cx == n - 1 && cy == m - 1) {
int[] tmp = new int[]{cx, cy};
ans.add(tmp);
return true;
}
matrix[cx][cy] = 1;
int[] tmp = new int[]{cx, cy};
ans.add(tmp);
if (process(cx - 1, cy, n, m, ans, matrix)) {
return true;
}
if (process(cx + 1, cy, n, m, ans, matrix)) {
return true;
}
if (process(cx, cy - 1, n, m, ans, matrix)) {
return true;
}
if (process(cx, cy + 1, n, m, ans, matrix)) {
return true;
}
matrix[cx][cy] = 0;
ans.remove(ans.size() - 1);
return false;
}
}