HDU 1241 是深搜算法的入门题目,递归实现。

原题目传送门: 

http://acm.hdu.edu.cn/showproblem.php?pid=1241

代码仅供参考,c++实现:

#include <iostream>
using namespace std;

char land[150][150];
int p,q;

void dfs(int x,int y){
    land[x][y] = '*';
    if(land[x-1][y]!= '@' && land[x+1][y] != '@' && land[x][y-1] != '@' && land[x][y+1] != '@' && land[x-1][y+1]!= '@' && land[x+1][y-1] != '@' && land[x-1][y-1] != '@' && land[x+1][y+1] != '@')
        return ;
    
    if(x+1 > 0 && y+1 > 0 && x+1 <= p && y+1 <= q && land[x+1][y+1]== '@') { dfs(x+1,y+1);  }
    if(x+1 > 0 && y-1 > 0 && x+1 <= p && y-1 <= q && land[x+1][y-1]== '@') { dfs(x+1,y-1);  }
    if(y-1 > 0 && x-1 > 0 && x-1 <= p && y-1 <= q && land[x-1][y-1]== '@') { dfs(x-1,y-1);  }
    if(y+1 > 0 && x-1 > 0 && x-1 <= p && y+1 <= q && land[x-1][y+1]== '@') { dfs(x-1,y+1);  }
    
    if(x+1 > 0 && y > 0 && x+1 <= p && y <= q && land[x+1][y]== '@') { dfs(x+1,y);  }
    if(x-1 > 0 && y > 0 && x-1 <= p && y <= q && land[x-1][y]== '@') { dfs(x-1,y);  }
    if(y-1 > 0 && x > 0 && x <= p && y-1 <= q && land[x][y-1]== '@') { dfs(x,y-1);  }
    if(y+1 > 0 && x > 0 && x <= p && y+1 <= q && land[x][y+1]== '@') { dfs(x,y+1);  }
   
    return ;
}
int main(int argc, const char * argv[]) {
    
    int num;
    cin>>p>>q;
    while(p>0 && q>0){
    
            num = 0;
            for(int i = 1; i <= p ;i++){
                for(int j = 1; j<= q; j++){
                    cin>>land[i][j];
                }
            }
            for(int i = 1; i <= p ;i++){
                for(int j = 1; j<= q; j++){
                    if(land[i][j] == '@'){
                        num++;
                        dfs(i,j);
                    }
                    
                }
            }
            cout<< num<<endl;
        cin>>p>>q;
    }
    return 0;
}

 

posted on 2015-02-21 05:33  雨傾晨叶  阅读(743)  评论(0编辑  收藏  举报