#include<bits/stdc++.h>
using namespace std;
const int N = 310;
char s[N][N];
bool st[N][N];
typedef pair<int,int> PII;
#define x first
#define y second
int n,m;
int f[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int distant[N][N];
int sx,sy;
void check(int &fx,int &fy) //引用类型变量 找到队列的
{ for(int i = 1; i <= n; i ++)
{ for(int j = 1; j <= m; j ++)
{ if(s[i][j] == s[fx][fy] && (i != fx || j != fy) )
{
fx = i;
fy = j;
return;
}
}
}
}
int bfs(int x,int y)
{ queue<PII> q; //定义个队列
q.push({x,y});
st[x][y] = true;
distant[x][y] = 0;
while(!q.empty())
{ auto t = q.front();
q.pop();
if(s[t.x][t.y] >= 'A' && s[t.x][t.y] <= 'Z') //找到传送装置的起点或者终点
{ int dx,dy;
dx = t.x;
dy = t.y;
check(dx,dy);
distant[dx][dy] = distant[t.x][t.y]; //时间赋值给另一个传送门
t.x = dx;
t.y = dy;
}
if(s[t.x][t.y] == '=') return distant[t.x][t.y];//如果是终点直接返回
for(int i = 0; i < 4; i ++)
{ int fx = t.x + f[i][0];
int fy = t.y + f[i][1];
if(fx >= 1 && fx <= n && fy >= 1 && fy <= m && !st[fx][fy] && s[fx][fy] != '#')
{
st[fx][fy] = true;
distant[fx][fy] = distant[t.x][t.y] + 1;
q.push({fx,fy});
}
}
}
}
int main(){
ios::sync_with_stdio(false); cin.tie(0);cout.tie(0);//读入加速
cin >> n >> m;
string s2;
int x,y;//标记入口点
for(int i = 1; i <= n; i ++) //读入时顺便找入口,以字符串类型读入
{ cin >> s2;
for(int j = 1; j <= m; j ++)
{ s[i][j] = s2[j-1];
if(s[i][j] == '@') //入口
{ x = i;
y = j;
}
}
}
cout << bfs(x,y) << endl;
return 0;
}
P1825 [USACO11OPEN]Corn Maze S
最新推荐文章于 2025-01-06 13:38:07 发布