Fork me on GitHub

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

【题目链接:NYOJ-82

#include<iostream>
#include<cstring>
using namespace std;
struct node{
    int x1;
    int y1;
    int num;
}arry[5];
const int MAXN = 25;
char Map[MAXN][MAXN];

int ac;
int havekey[5];
int findkey[5];

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 - 1,y);
        dfs(x + 1,y);
        dfs(x,y - 1);
        dfs(x,y + 1);
        check();
    }
}
void check(){
    for(int i = 0;i < 5;i++){
        if(arry[i].num){
            if(findkey[i] == havekey[i]){
                Map[arry[i].x1][arry[i].y1] = 'X';
                dfs(arry[i].x1 + 1,arry[i].y1);
                dfs(arry[i].x1 - 1,arry[i].y1);
                dfs(arry[i].x1,arry[i].y1 + 1);
                dfs(arry[i].x1,arry[i].y1 - 1);
            }
        }
    }
}
int main(){
    int m,n;
    while((cin >> m >> n) && (m || n)){
        memset(havekey,0,sizeof(havekey));
        memset(findkey,0,sizeof(findkey));
        memset(arry,0,sizeof(arry));
        memset(Map,'X',sizeof(Map));//初始边界,否则递归搜索时,会越界空指针 
        ac = 0;

        int a1,b1;
        
        for(int i = 1;i <= m;i++){
            for(int j = 1;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 0;
}
//4 4
//S.X.
//a.X.
//..XG
//.... 
//3 4
//S.Xa
//.aXB
//b.AG
//0 0

 

posted @ 2015-05-18 23:36  郑斌blog  阅读(729)  评论(0编辑  收藏  举报