版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sugarbliss/article/details/88220673
题目链接:https://ac.nowcoder.com/acm/contest/330/C
思路:BFS多开一维标记状态,然后在搜索的时候单独判断一下遇到'@'的情况就好了(将切换状态和不变都扔入队列中),然后按题意模拟即可。
AC代码:
#include <bits/stdc++.h>
using namespace std;
struct node
{
int x, y, sta, step;
}S, T, Now, Net;
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
bool vis[105][105][2];
string mp[105];
int n, m;
bool Check(int x, int y, int z)
{
if(x < 0 || y < 0 || x >= n || y >= m)return false;
if(mp[x][y] == '#') return false;
if(vis[x][y][z] == true) return false;
if((z == 0 && mp[x][y] == 'w') || (z == 1 && mp[x][y] == '~')) return false;
return true;
}
int BFS()
{
memset(vis,false,sizeof(vis));
queue <node> Q;
S.sta = 0, S.step = 0;
Q.push(S);
while(!Q.empty())
{
Now = Q.front();
Q.pop();
if(Now.x == T.x && Now.y == T.y) return Now.step;
if(mp[Now.x][Now.y] == '@' && vis[Now.x][Now.y][Now.sta^1] == false)
{
Net.x = Now.x, Net.y = Now.y;
Net.step = Now.step + 1;
Net.sta = Now.sta ^ 1;
vis[Net.x][Net.y][Net.sta] = true;
Q.push(Net);
}
for(int i = 0; i < 4; i++)
{
Net.x = Now.x + dir[i][0];
Net.y = Now.y + dir[i][1];
if(Check(Net.x, Net.y, Now.sta))
{
Net.step = Now.step + 1;
Net.sta = Now.sta;
vis[Net.x][Net.y][Net.sta] = true;
Q.push(Net);
}
}
}
return -1;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++)
cin >> mp[i];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
if(mp[i][j] == 'S')
S.x = i, S.y = j;
if(mp[i][j] == 'T')
T.x = i, T.y = j;
}
int ans = BFS();
printf("%d\n",ans);
}