Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 3245 | Accepted: 1022 |
Description
Input
Output
Sample Input
4 4 S.X. a.X. ..XG .... 3 4 S.Xa .aXB b.AG 0 0
Sample Output
YES NO
Source
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
bool vis[20][20];
int dir[4][2]={-1,0,1,0,0,-1,0,1};
char mat[25][25];
int r,c,sx,sy,ex,ey,flag,ok,p;
int totalKey[5], haveKey[5];
void dfs(int x, int y){
if(x==ex && y==ey) ok=1;
if(mat[x][y]=='X' || vis[x][y]) return;
if(islower(mat[x][y])) {haveKey[mat[x][y]-'a']++, mat[x][y]='.',flag++;}
if(mat[x][y]=='A' || mat[x][y]=='B' || mat[x][y]=='C' || mat[x][y]=='D' || mat[x][y]=='E'){
if(haveKey[mat[x][y]-'A']==totalKey[mat[x][y]-'A'] && haveKey[mat[x][y]-'A']!=0) mat[x][y]='.'; //&& 寫成 || 找了半天錯
else return;
}
vis[x][y] = true;
for(int i=0; i<4; i++){
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx<0 || tx>r-1 || ty<0 || ty>c-1) continue;
dfs(tx,ty);
}
}
int main()
{
while(cin>>r>>c &&r+c){
flag=ok=0;
memset(vis,false,sizeof(vis));
memset(mat,'\0',sizeof(mat));
memset(haveKey,0,sizeof(haveKey));
memset(totalKey,0,sizeof(totalKey));
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
cin>>mat[i][j];
if(islower(mat[i][j])) totalKey[mat[i][j]-'a']++;
if(mat[i][j]=='S') sx = i, sy = j, mat[i][j]='.';
if(mat[i][j]=='G') ex = i, ey = j; //一開始ey寫成sy,找了半天錯
}
}
dfs(sx,sy);p=flag;
while(true){
memset(vis,false,sizeof(vis));
dfs(sx,sy);
if(flag==p) break;
else p=flag;
}
// int m = 405; //棋盤是20*20的,所以最多搜索400次,其實肯定不可能這麼多,懶得推證了
// while(m--){
// dfs(sx,sy);
// memset(vis,false,sizeof(vis));
// }
if(ok) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}