要求输入两个整数m,n表示迷宫矩阵大小(m*n),然后输入迷宫矩阵,0表示死路,1表示通路。令迷宫入口坐标为(0,0)出口坐标为(m-1,n-1)。
要求输出走出迷宫的所有路线
package 走迷宫2;
import java.util.Scanner;
public class Main {
static int[][] mk = new int[100][100];
static int m;
static int n;
static String s = ""; //存储可达的路径
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
m = sc.nextInt(); //输入行数
n = sc.nextInt(); //输入列数
int[][] t = new int[m][n]; //迷宫数组
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
t[i][j] = sc.nextInt(); // 将数据读入到数组中
}
}
dfs(0, 0, t); // 参数1x坐标 参数2y坐标 参数3数组t
}
public static void dfs(int x, int y, int[][] t) {
// 1.如果x坐标小于0 y坐标小于0 return
if (x < 0 || y < 0)
return;
//2.如果x坐标大于m-1 y坐标大于m-1 mk[x][y] != 0表示已经被走过 return
if (x > m - 1 || y > m - 1 || mk[x][y] != 0)
return;
//3.如果 t[x][y] == 0 表示死路 return
if (t[x][y] == 0)
return;
//如果 x == m - 1 && y == n - 1表示到达终点
if (x == m - 1 && y == n - 1) {
s = s + "(" + x + "," + y + ")"+"!";
System.out.println("找到路线:" + s);
return;
}
String temp = s;
s = s + "(" + x + "," + y + ")" + "-"; // 记录路线
// ----------------将走过的路标记
mk[x][y] = 1;
// 向四个方向搜索
dfs(x + 1, y, t);
dfs(x, y + 1, t);
dfs(x, y - 1, t);
dfs(x - 1, y, t);
//------------- 将路线和标记恢复成上一次的状态
mk[x][y] = 0;
s = temp;
}
}