Topic Connection: http://acm.nyist.net/JudgeOnline/problem.php?pid=82 This topic added a door and a key to the base BFS, to gathered up all the keys to open the door, so we have to deal with the gate special. 1. First count the number of keys, and then write down the location of the door. 2. To carry out BFS, when encountering the key, the team, count the various types of keys have been found, and then determine whether the key gathered up, if the gathered up, find the corresponding door, if the door has been visited before, then the door queue. (This door may be blocked by obstruction, can not go in, so can not directly join, only the previous access to join). 3. If a door is encountered, determine if the key is gathered up, if the alignment, the queue, Mark has been visited; 4. Other press the normal BFS.
#include <iostream> #include <cstring> #include <queue> using namespace std; struct point {int x, y;}
S,E,MEN[6];
int n,m;
int h[4][2]={-1,0,1,0,0,1,0,-1};
int yaosum[6],findyao[6],bz[30][30];
Char map[30][30];
Queue<point> Q;
int BFS (point s) {int. I; point temp,t;
while (!q.empty ()) Q.pop (); Q.push (s);
Bz[s.x][s.y]=1;
while (!q.empty ()) {Temp=q.front (); Q.pop ();
if (TEMP.X==E.X&&TEMP.Y==E.Y) return 1; for (i=0;i<4;i++) {t.x=temp.x+h[i][0];
T.Y=TEMP.Y+H[I][1]; if (t.x>=0&&t.x<n&&t.y>=0&&t.y<m&&map[t.x][t.y]!= ' x ') {if (map[t.x][ T.y]>= ' A ' &&map[t.x][t.y]<= ' E ' &&!bz[t.x][t.y])//is the door to see if you can open {if (findyao[map[t.x][t.y]-' a ']==
yaosum[map[t.x][t.y]-' A '])//Key-QI, you can open {Q.push (t); bz[t.x][t.y]=1; } else bz[t.x][t.y]=1;
Cannot open, first mark accessed} else if (map[t.x][t.y]>= ' a ' &&map[t.x][t.y]<= ' e ' &&!bz[t.x][t.y])//is the key {findyao[map[t.x][t.y]-' a ']++; Q.push (t);
Bz[t.x][t.y]=1;
Determine if the key is already gathered up, and if the corresponding door has been visited, if the key is the same, the door has been visited before, you can queue the door if (findyao[map[t.x][t.y]-' a ']==yaosum[map[t.x][t.y]-' a ']) { Point m; m.x=men[map[t.x][t.y]-' a '].x;
m.y=men[map[t.x][t.y]-' a '].y; if (Bz[m.x][m.y]) Q.push (m); Door Queue}} else if ((map[t.x][t.y]== '. ' | |
map[t.x][t.y]== ' G ') &&!bz[t.x][t.y]) {Q.push (t); bz[t.x][t.y]=1;
}}}} return 0;
} int main (int argc, char *argv[]) {int i,j;
while (cin>>n>>m&& (n+m)) {memset (yaosum,0,sizeof (yaosum));
memset (findyao,0,sizeof (Findyao));
memset (bz,0,sizeof (BZ));
for (i=0;i<n;i++) for (j=0;j<m;j++) {cin>>map[i][j];
if (map[i][j]== ' S ') {s.x=i;s.y=j;}
else if (map[i][j]== ' G ') {e.x=i; e.y=j;}
else if (map[i][j]>= ' a ' &&map[i][j]<= ' e ') yaosum[map[i][j]-' a ']++; else if (map[i][j]>= ' a ' &&map[i][j]<= ' E ') {men[map[i][j]-' a '].x=i; men[map[i][j]-' a '].y=j;
}} if (BFS (s)) cout<< "YES" <<endl;
else cout<< "NO" <<endl;
} return 0; }