广度优先收索(迷宫)
#include <iostream> #include <queue> using namespace std; struct n { int a,b; }; queue<n>k; int m[100][100],b[100][100]; int main(){ int a,c,sx,sy,ex,ey; cin>>a>>c; for(int i=1;i<=a;i++){ for(int j=1;j<=c;j++){ char tmp;cin>>tmp; if(tmp=='X'){ m[i][j]=0; } if(tmp=='.'){ m[i][j]=1; } if(tmp=='S'){ m[i][j]=1; sx=i;sy=j; } if(tmp=='T'){ m[i][j]=1; ex=i;ey=j; } } } n now,tmp; int cnt=0; now.a=sx,now.b=sy,b[sx][sy]=0,k.push(now); int aa[4][2]={{-1,0},{1,0},{0,1},{0,-1}}; while(k.size()!=0){ now=k.front(); k.pop(); if(now.a==ex && now.b==ey){ cout<<b[now.a][now.b]+1; return 0; } for(int i=0;i<4;i++){ if(m[now.a+aa[i][0]][now.b+aa[i][1]] && b[now.a+aa[i][0]][now.b+aa[i][1]]==0){ tmp.a=now.a+aa[i][0]; tmp.b=now.b+aa[i][1]; b[now.a+aa[i][0]][now.b+aa[i][1]]=b[now.a][now.b]+1; k.push(tmp); } } } cout<<0; }