复习一下经典bfs
作者:
巷港
,
2022-03-16 00:37:33
,
所有人可见
,
阅读 144
仙岛求药
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int,int>PII;
#define x first
#define y second
const int N = 310;
int d[N][N];
char g[N][N];
int n,m;
int bfs(PII start)
{
queue<PII>q;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
memset(d,-1,sizeof d);
q.push(start);
d[start.x][start.y]=0;
while (q.size())
{
PII t = q.front();
q.pop();
for (int i=0;i<4;i++)
{
int x = t.x+dx[i];
int y = t.y+dy[i];
if (x<0||x>=n||y<0||y>=m) continue;
if (g[x][y]=='#') continue;
if (d[x][y]!=-1) continue;
d[x][y]=d[t.x][t.y]+1;
if (g[x][y]=='*') return d[x][y];
q.push({x,y});
}
}
return -1;
}
int main()
{
while (scanf("%d%d",&n,&m),n||m)
{
for (int i=0;i<n;i++) scanf("%s",g[i]);
PII start;
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
if (g[i][j]=='@') start={i,j};
int ans=bfs(start);
printf("%d\n",ans);
}
return 0;
}