FZU 2285 迷宫寻宝

时间:2022-08-03 19:24:46

思路:

bfs求最短路径。

 #include<stdio.h>
#include<iostream>
#include<queue>
#include<cstring>
#define maxn 105
using namespace std;
int sx, sy, ex, ey;
char map[][];
char vis[][];
int dic[][] = { { -, },{ ,- },{ , },{ , } };//4个方向
int res;
struct node {
int x, y, step;
};
int n;
bool check(int x, int y)
{
if (x >= && x < n&&y >= && y < n&&map[x][y] != '#'&&vis[x][y] !=)
return true;
//printf("x=%d y=%d c=%c\n", x, y,map[x][y]);
return false;
} void bfs()
{
queue<node> q;
node a;
node next;
a.x = sx;
a.y = sy;
a.step = ;
vis[a.x][a.y] = ;
q.push(a);
while (!q.empty())
{
a = q.front();
q.pop();
for (int i = ; i<; i++)
{
next = a;
next.x += dic[i][];
next.y += dic[i][];
next.step = a.step + ;
if (next.x == ex&&next.y == ey)//找到出口
{
res = next.step;
// printf("res=%d\n", res);
return;
}
if (check(next.x, next.y))//检查合法性
{
vis[next.x][next.y] = ;
//printf("vis[%d][%d]=1\n", next.x, next.y);
q.push(next);
}
}
}
res = -;
}
int main()
{
while (scanf("%d", &n) == )
{
for (int i = ; i<n; i++)
scanf("%s", &map[i]);
memset(vis, , sizeof(vis));
//for (int i = 0; i < n; i++)
//printf("%s\n", map[i]);
for (int i = ; i<n; i++)
{
for (int j = ; j<n; j++)
{
if (map[i][j] == 'S')
{
sx = i;
sy = j;
}
if (map[i][j] == 'E')
{
ex = i;
ey = j;
}
}
}
//printf("sx=%d sy=%d ex=%d ey=%d\n", sx, sy, ex, ey);
bfs();
printf("%d\n", res);
}
return ;
}