import java.util.Scanner;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class 深度优先 {
/**
* 迷宫问题
* 一个n*m的迷宫,走到某处的最短路径 1表示有障碍物
* 输入格式
* 5 4 5行4列
* 0 0 1 0 迷宫第图 1表示障碍物
* 0 0 0 0
* 0 0 1 0
* 0 1 0 0
* 0 0 0 1
* 1 1 4 3 1 1 表示起点 4 3 表示达到的位置
* 输出格式
* 7 最短走7次
*/
static int[][] a=new int[51][51]; // 迷宫
static int[][] book=new int[51][51]; // 标记
static int min=51; // 最短路径长度
static int n,m;
static int endx,endy; // 到达位置
public static void main(String[] args) {
int startx,starty; // 起始位置
Scanner scanner=new Scanner(System.in);
n=scanner.nextInt(); // n行
m=scanner.nextInt(); // m列
// 接收迷宫地图
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
a[i][j]=scanner.nextInt();
}
}
// 读入起始点和到达点
startx=scanner.nextInt();
starty=scanner.nextInt();
endx=scanner.nextInt();
endy=scanner.nextInt();
// 从起始点开始搜索
book[startx][starty]=1; // 先标记该位置已遍历过
dfs(startx,starty,0);
System.out.println(min);
}
// x表示起点x坐标,y表示起点y坐标,step走的步数
public static void dfs(int x,int y,int step){
int[][] next={{0,1}, // 向右走
{1,0}, // 向下走
{0,-1}, // 向左走
{-1,0}, // 向上走
};
int tx,ty;
// 边界条件,判断是否到达点
if (x==endx&&y==endy) {
// 更新最小值
if(step<min){
min=step;
}
return;
}
// 遍历所有走法,四种
for (int i = 0; i < 4; i++) {
tx=x+next[i][0];
ty=y+next[i][1]; // 下一点坐标
// 判断是否越界
if (tx<1||tx>n||ty<1||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; // 还原
}
}
}
}
蓝桥杯 Java 深度优先
最新推荐文章于 2024-07-29 14:22:26 发布