题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.Scanner;
import java.util.Stack;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
private static Stack<String> walkPath = new Stack<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt();
int m = in.nextInt();
int[][] nums = new int[n][m];
// 构建二维数组
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
nums[i][j] = in.nextInt();
}
}
walk(nums, 0, 0);
// 遍历迷宫
while (!walkPath.isEmpty()) {
System.out.println(walkPath.pop());
}
}
}
/**
* 从什么位置开始走 2表示路已经走过了 但是走不通 3 表示可是走
*
* @param nums
* 数组
* @param col
* 行
* @param row
* 列
* @return
*/
private static boolean walk(int[][] nums, int col, int row) {
// 检查是否越界
if (row < 0 || col < 0 || col >= nums.length || row >= nums[0].length) {
return false;
}
// 重点已经等于3 代表已经找到了
if (nums[nums.length - 1][nums[0].length - 1] == 3) {
return true;
}
if (nums[col][row] == 0) { // 当前这个点还没有走过
// 需要假定现在这个点是能够走通的
nums[col][row] = 3;
if (walk(nums, col - 1, row)) {
walkPath.add("(" + col + "," + row + ")");
return true;
} else if (walk(nums, col, row - 1)) {
walkPath.add("(" + col + "," + row + ")");
return true;
} else if (walk(nums, col + 1, row)) {
walkPath.add("(" + col + "," + row + ")");
return true;
} else if (walk(nums, col, row + 1)) {
walkPath.add("(" + col + "," + row + ")");
return true;
}
// 其实这个点四个方向都是死路
nums[col][row] = 2;
}
// 走过并且没到重点 那就是没找对路
return false;
}
}
阿里云工作强度 710人发布