【DFS】NYOJ-82 迷宫寻宝(一)-条件迷宫问题

时间:2022-03-16 05:17:29

【题目链接:NYOJ-82

#include<iostream>
#include<cstring>
using namespace std;
struct node{
int x1;
int y1;
int num;
}arry[];
const int MAXN = ;
char Map[MAXN][MAXN]; int ac;
int havekey[];
int findkey[]; void check(); void dfs(int x,int y){
if(Map[x][y] != 'X'){
switch(Map[x][y]){
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
findkey[Map[x][y] - 'a']++;
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
arry[Map[x][y] - 'A'].x1 = x;
arry[Map[x][y] - 'A'].y1 = y;
arry[Map[x][y] - 'A'].num++;
return;
case 'G':
ac = true;
return;
}
Map[x][y] = 'X'; //标记已经走过
dfs(x - ,y);
dfs(x + ,y);
dfs(x,y - );
dfs(x,y + );
check();
}
}
void check(){
for(int i = ;i < ;i++){
if(arry[i].num){
if(findkey[i] == havekey[i]){
Map[arry[i].x1][arry[i].y1] = 'X';
dfs(arry[i].x1 + ,arry[i].y1);
dfs(arry[i].x1 - ,arry[i].y1);
dfs(arry[i].x1,arry[i].y1 + );
dfs(arry[i].x1,arry[i].y1 - );
}
}
}
}
int main(){
int m,n;
while((cin >> m >> n) && (m || n)){
memset(havekey,,sizeof(havekey));
memset(findkey,,sizeof(findkey));
memset(arry,,sizeof(arry));
memset(Map,'X',sizeof(Map));//初始边界,否则递归搜索时,会越界空指针
ac = ; int a1,b1; for(int i = ;i <= m;i++){
for(int j = ;j <= n;j++){
cin >> Map[i][j];
if(Map[i][j] == 'S')
a1 = i,b1 = j;
else if(Map[i][j] >= 'a' && Map[i][j] <= 'e')//将其保存至数组
havekey[Map[i][j] - 'a']++;
}
}
dfs(a1,b1);
if(ac){
cout << "YES" << endl;
}else cout << "NO" << endl;
}
return ;
}
//4 4
//S.X.
//a.X.
//..XG
//....
//3 4
//S.Xa
//.aXB
//b.AG
//0 0