标签:
3 5 6 XXXXXX XZ..ZX XXXXXX M.G... ...... 5 6 XXXXXX XZZ..X XXXXXX M..... ..G... 10 10 .......... ..X....... ..M.X...X. X......... .X..X.X.X. .........X ..XX....X. X....G...X ...ZX.X... ...Z..X..X
1 1 -1
#include<stdio.h> #include<queue> #include<math.h> #include<string.h> #include<stdlib.h> using namespace std; char map[810][810]; int step[4][2]= {1,0,-1,0,0,1,0,-1}; struct node { int x,y; } M,G,Z[2]; int num_of_step,n,m; queue<node> q[3]; bool ghost(node a) { for(int i=0; i<2; i++) { if(abs(a.x-Z[i].x)+abs(a.y-Z[i].y) <= 2*num_of_step)// return false;//被抓 } return true; } bool check(node b) { if(b.x>=0&&b.y>=0&&b.x<n&&b.y<m&&map[b.x][b.y]!='X') return true; return false; } bool BFS(int people,int time,int start,int endd) { node cur,next; q[2]=q[people]; for(int i=0; i<time; i++) { while(!q[2].empty()) { cur=q[2].front(); q[2].pop(); q[people].pop(); if(ghost(cur)) //如果被抓 { for(int i=0; i<4; i++) { next=cur; next.x+=step[i][0]; next.y+=step[i][1]; if(ghost(next)&&check(next)&&map[next.x][next.y]!=start) { if(map[next.x][next.y]==endd) return true; map[next.x][next.y]=start; q[people].push(next); } } } } q[2]=q[people]; } return false; } int solve () { for(int i=0; i<3; i++) ////clear { while(!q[i].empty()) q[i].pop(); } num_of_step=0; q[0].push(M); q[1].push(G); while(!q[0].empty()&&!q[1].empty())//// { num_of_step++; if(BFS(0,3,'M','G')||BFS(1,1,'G','M'))//// return num_of_step; } return -1; } int main (void) { int N; scanf("%d",&N); while(N--) { int cnt=0; scanf("%d%d",&n,&m); //getchar(); for(int i=0; i<n; i++) { scanf("%s",map[i]); for(int ii=0; ii<m; ii++) { if(map[i][ii]=='M') M.x=i,M.y=ii; else if(map[i][ii]=='G') G.x=i,G.y=ii; else if(map[i][ii]=='Z') Z[cnt].x=i,Z[cnt].y=ii,++cnt; } } //getchar(); printf("%d\n",solve()); } return 0; }
..X....... ..M.X...X. X......... .X..X.X.X. .........X ..XX....X. X....G...X ...ZX.X... ...Z..X..X
1 1 -1
HDU 3085 Nightmare Ⅱ【BFS +曼哈顿距离+综合性较强】
标签:
原文地址:http://blog.csdn.net/qq_24653023/article/details/52085963