广度优先收索(T148526)
#include <iostream> #include <queue> using namespace std; struct point { int x,y,bu; }; int sx=1,sy=1,ex,ey,m[1000][1000],b[1000][1000],ssx[100],ssy[100]; queue <point>t; int main() { int n,m2,v=0;cin>>n>>m2; ex=n;ey=m2; for(int i=1;i<=n;i++){ for(int j=1;j<=m2;j++){ char tmp;cin>>tmp; if(tmp=='.'){ m[i][j]=1; } if(tmp=='#'){ m[i][j]=0; } if(tmp=='$'){ m[i][j]=3; ssx[v]=i; ssy[v]=j; v++; } } } int meet=0; point now,tmp; now.x=sx,now.y=sy,now.bu=0,b[now.x][now.y]=1; t.push(now); int aa[4][2]={{-1,0},{1,0},{0,1},{0,-1}}; while(t.size()!=0){ now=t.front(); t.pop(); if(now.x==ex && now.y==ey){ cout<<b[now.x][now.y]+1; return 0; } if(m[now.x][now.y]==3 && meet==0){ meet=1; for(int i=0;i<v;i++){ tmp.x=ssx[i]; tmp.y=ssy[i]; tmp.bu=now.bu; t.push(tmp); b[now.x][now.y]=1; } } for(int i=0;i<4;i++){ if(m[now.x+aa[i][0]][now.y+aa[i][1]] && b[now.x+aa[i][0]][now.y+aa[i][1]]==0){ tmp.x=now.x+aa[i][0]; tmp.y=now.y+aa[i][1]; b[now.x+aa[i][0]][now.y+aa[i][1]]=b[now.x][now.y]+1; t.push(tmp); } } } cout<<-1; return 0; }