package com.xjj.Ah;
import java.util.Scanner;
/*---深度优先搜索---
* 1.迷宫解救
*
* */
public class Ah_4_2 {
static int[][] a = new int[51][51]; //存迷宫
static int[][] book = new int[51][51]; //标记是否走过
static int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}}; //方向数组,右下左上(顺时针),精妙之处(方便递归枚举)
static int p,q,n,m,min = Integer.MAX_VALUE;
public void dfs(int x, int y, int step){
if (x == p && y == q) { //该坐标等于搜索物的坐标
if (step < min) { //更新最短路径
min = step;
}
return; //返回到上一步
}
//枚举方向4种可能
for(int k = 0; k <= 3; k++){
int tx = x + dir[k][0];
int ty = y + dir[k][1];
//判断是否越界
if (tx<1 || ty<1 || tx>n || ty>m) {
continue;
}
//判断不为障碍物并且不在路径中
if (a[tx][ty] == 0 && book[tx][ty] == 0) {
book[tx][ty] = 1; //该点已经在路径中
dfs(tx, ty, step+1); //开始尝试下一点
book[tx][ty] = 0; //尝试结束,取消该点的标记
}
}
}
public static void main(String[] args) {
System.out.println("输入迷宫(n为行,m为列):");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++){
a[i][j] =scanner.nextInt();
}
p = 4;
q = 3;
Ah_4_2 ah = new Ah_4_2();
ah.dfs(1, 1, 0);
System.out.println("最短路径为: " + min);
}
}
深度搜索--迷宫解救
最新推荐文章于 2019-02-22 11:26:00 发布