码迷,mamicode.com
首页 > 其他好文 > 详细

深搜基础题目 杭电 HDU 1241

时间:2015-02-21 06:29:47      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

 

深搜基础题目 杭电 HDU 1241

标签:

原文地址:http://www.cnblogs.com/sweetiemelody/p/4296824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!