练习dfs和bfs的好题。
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<cmath> #include<map> #include<set> #include<vector> #include<algorithm> #include<stack> #include<queue> #include<cctype> #include<sstream> using namespace std; #define pii pair<int,int> #define LL long long int const int eps=1e-8; const int INF=1000000000; const int maxnm=100+10; int ans,n,m,k,d[5][5]; int dx[4]= {1,-1,0,0}; int dy[4]= {0,0,1,-1}; char maps[maxnm][maxnm]; int had[maxnm][maxnm]; struct Precious { int x,y; bool used; } p[5]; int Bfs(int from,int to); bool Dfs(int id,int now,int step); void ini(); int main() { //freopen("in8.txt","r",stdin); while(scanf("%d%d",&n,&m)==2) { if(n==0&&m==0) break; ini(); for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) { cin>>maps[i][j]; if(maps[i][j]=='@') { p[0].x=i; p[0].y=j; } } } scanf("%d",&k); for(int i=1; i<=k; i++) { int xx,yy; scanf("%d%d",&xx,&yy); p[i].x=xx; p[i].y=yy; } if(Dfs(0,0,0)) { printf("%d ",ans); } else { printf("-1 "); } } return 0; } void ini() { memset(d,-1,sizeof(d)); ans=INF; for(int i=0; i<5; i++) { p[i].used=0; } } int Bfs(int from,int to) { if(d[from][to]!=-1) return d[from][to]; if((p[from].x==p[to].x)&&(p[from].y==p[to].y)) { return d[from][to]=0; } else { queue<pii>q; memset(had,0,sizeof(had)); q.push(make_pair(p[from].x,p[from].y)); had[p[from].x][p[from].y]=1; while(!q.empty()) { int tx=q.front().first; int ty=q.front().second; q.pop(); for(int i=0; i<4; i++) { int X=tx+dx[i]; int Y=ty+dy[i]; if(X>=1&&X<=n&&Y>=1&&Y<=m) { if(had[X][Y]||maps[X][Y]=='#') { continue; } else { q.push(make_pair(X,Y)); had[X][Y]=had[tx][ty]+1; if(X==p[to].x&&Y==p[to].y) { return d[from][to]=had[X][Y]-1; } } } } } return d[from][to]=-2; } } bool Dfs(int id,int now,int step) //id表示现在在哪点,now表示已经拿了几个,step表示目前一共走了几步 { bool w=0; p[id].used=1; if(now==k) { //cout<<"***"<<step<<endl; ans=min(ans,step); p[id].used=0; return true; } else { for(int i=1; i<=k; i++) { if(p[i].used==0) { int stt=Bfs(id,i); if(stt==-2) { p[id].used=0; return false; } else { if(Dfs(i,now+1,step+stt)) { w=1; } } } } if(w==1) { p[id].used=0; return true; } else { p[id].used=0; return false; } } }