#include <stdio.h>
#include <string.h>
#include <queue>
#include <string.h>
using namespace std;
const int INF = 0x3f3f3f3f; // 无限大
const int maxn = 25;
int g[maxn][maxn], vis[maxn][maxn];
// g为图的数组 vis标记访问过的点
int n, m, sx, sy, ans; // sx sy 为起点坐标
int dir[4][2] = { {-1, 0}, // 向上走
{1, 0}, // 向下走
{0, -1}, // 向左走
{0, 1} }; // 向右走
// x,y表示当前坐标
// step代表已经走过的步数
void dfs(int x, int y, int step) {
int tx, ty, k;
//判断是否到达终点
if (g[x][y] == 3) { // p,q代表终点位置
//更新最小值
if (step < ans)
ans = step;
return;
}
//枚举四种走法
for (k = 0; k < 4; k++) {
//计算下一个点的坐标
tx = x + dir[k][0];
ty = y + dir[k][1];
//判断是否越界
if (tx < 0 || tx >= n || ty < 0 || ty >= m)
continue;
//不是障碍 且 没访问过
if (g[tx][ty] != 0 && vis[tx][ty] == 0) {
vis[tx][ty] = 1; //标记这个点已经走过
dfs(tx, ty, step + 1); //开始尝试下一个点
vis[tx][ty] = 0; //尝试结束,取消这个点的标记
}
}
return;
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
for (int i = 0 ; i < n ; i++) {
for (int j = 0 ; j < m ; j++) {
vis[i][j] = 0;
scanf("%d", &g[i][j]);
if (g[i][j] == 2) {
sx = i;
sy = j;
}
}
}
ans = INF; // INF 无限大
dfs(sx, sy, 0);
printf("%d\n", ans == INF ? -1 : ans);
}
return 0;
}
/*
8 8
2 1 0 1 0 0 1 0
1 0 1 1 1 1 1 0
1 1 1 0 0 0 1 1
0 1 0 0 0 0 1 1
0 1 1 1 1 0 1 0
0 0 0 1 1 0 1 0
1 1 0 0 1 1 1 1
0 1 1 1 1 0 1 3
14
dfs
最新推荐文章于 2024-08-13 13:52:30 发布