package 万能的搜索;
import java.util.Scanner;
/**
* 深搜最短路径
*
*
* */
public class Demo02 {
static int[][] a;
static int[][] b;
static int min,q,p,m,n;
public static void dfs(int startx,int starty,int step) {
// 先写退出条件
if(startx == p && starty==q) {
if(step < min) {
min = step;
}
return ;
}
//记录下一个坐标
int tx,ty;
// 相当于一个方向矩阵
int next[][]= {{0,1},{1,0},{0,-1},{-1,0}};
//枚举各种情况
for(int k=0;k<4;k++) {
// 先移动
tx = startx + next[k][0];
ty = starty + next[k][1];
// 将不合适的去掉
if(tx < 1 || tx >n || ty<1 || ty>m) {
continue;
}
if(b[tx][ty]==0 && a[tx][ty]==0) {
b[tx][ty] = 1;
dfs(tx,ty,step+1);
b[tx][ty] = 0; // 因为就当你找到了,但可能不是最短的,所以需要取消标记
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
min = Integer.MAX_VALUE;
n = in.nextInt();
m = in.nextInt();
a = new int[n+1][m+1];
b = new int[n+1][m+1];
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
a[i][j] = in.nextInt();
}
}
int startx = in.nextInt();
int starty = in.nextInt();
p = in.nextInt();
q = in.nextInt();
b[startx][starty] = 1;
dfs(startx,starty,0);
System.out.println(min);
}
}
/*
*
* 5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3
* 答案是:7
* */
深搜最短路径
最新推荐文章于 2023-11-24 12:39:13 发布