3 5
T..##
#.#.S
#...#
7
#pragma GCC optimize(2) #include<bits/stdc++.h> using namespace std; typedef long long ll; inline int read() { int x=0,f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} return x*f; } const int INF=0x3f3f3f3f; const int maxn=110; struct node{ int x,y; int st; }; int dir[4][2]={-1,0,1,0,0,-1,0,1}; char a[maxn][maxn]; int vis[maxn][maxn]; int n,m; int bfs(int u,int v){ node tmp,nex; tmp.x=u; tmp.y=v; tmp.st=0; queue<node>q; q.push(tmp); while(!q.empty()){ tmp=q.front(); q.pop(); for(int i=0;i<4;i++){ nex.x=tmp.x+dir[i][0]; nex.y=tmp.y+dir[i][1]; nex.st=tmp.st+1; if(nex.x<0||nex.y<0||nex.x>n||nex.y>m||a[nex.x][nex.y]==‘#‘||vis[nex.x][nex.y]==1)continue; vis[nex.x][nex.y]=1; if(a[nex.x][nex.y]==‘T‘){ return nex.st; } q.push(nex); } } } int main(){ cin>>n>>m; int x1,y1;//起点 for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cin>>a[i][j]; if(a[i][j]==‘S‘){ x1=i; y1=j; } } } int sum=bfs(x1,y1); cout<<sum<<endl; }
原文:https://www.cnblogs.com/lipu123/p/12805950.html