AcWing 1099. 仙岛求药
原题链接
简单
作者:
哈哈哈hh
,
2020-06-27 18:07:22
,
所有人可见
,
阅读 501
来自弱鸡的标准dfs
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 310;
char a[N][N];
int dis[N][N];
bool st[N][N];
int T,x,y,endx,endy,n,m;
static int pos[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int bfs()
{
memset(dis, 0, sizeof dis);
memset(st,false,sizeof st);
queue<pair<int,int>> q;
q.push({x,y});
dis[x][y] = 0;
while(!q.empty())
{
auto tmp = q.front();
q.pop();
if(tmp.first == endx && tmp.second == endy)
{
return dis[tmp.first][tmp.second];
}
for(int i = 0; i < 4; i++)
{
int nx = tmp.first + pos[i][0];
int ny = tmp.second + pos[i][1];
if(nx < 0 || nx >= n || ny < 0 || ny >=m
|| st[nx][ny] == true || a[nx][ny] == '#')
continue;
q.push({nx,ny});
dis[nx][ny] = dis[tmp.first][tmp.second] + 1;
st[nx][ny] = true;
}
}
return -1;
}
int main()
{
while(cin >> n >> m, n || m)
{
for(int i = 0; i < n; i++)
{
for(int j =0; j < m; j++)
{
cin >> a[i][j];
if(a[i][j] == '@')
{
x = i;
y = j;
}
if(a[i][j] == '*')
{
endx = i;
endy = j;
}
}
}
cout << bfs() <<endl;
}
}