首页 > 其他 > 详细

HDU 1312 ----- Red and Black 入门搜索 BFS解法

时间:2015-12-04 22:34:26      阅读:210      评论:0      收藏:0      [点我收藏+]

HDU 1312 ----- Red and Black  入门搜索   http://acm.hdu.edu.cn/showproblem.php?pid=1312

 

技术分享
/*HDU 1312 ----- Red and Black  入门搜索 BFS解法*/
#include <cstdio>
#include <queue>
using namespace std;

int n, m; //n行m列
int cnt;
char mapp[25][25];
int dirx[4] = { -1, 1, 0, 0 }; 
int diry[4] = { 0, 0, -1, 1 }; //用于循环来访问4个方向
struct Node{
    int x, y;
};
queue<Node> q;

void bfs(){
    /*队不为空时 表明还可以近一步搜索*/
    /*在队中的点都是已访问过、但需近一步访问周围四个方向的点的点*/
    while (!q.empty()){
        Node tmp = q.front();
        q.pop();
        Node tmp2;
        /*近一步判断该点的四个方向四否可以访问*/
        for (int i = 0; i < 4; ++i){
            //tmp2即为4个方向的点
            tmp2.x = tmp.x + dirx[i];
            tmp2.y = tmp.y + diry[i];
            if (tmp2.x >= 0 && tmp2.x < n && tmp2.y >= 0 && tmp2.y < m
                && mapp[tmp2.x][tmp2.y] != #){
                //该点可访问
                ++cnt;
                mapp[tmp2.x][tmp2.y] = #; //访问过后标记为不可访问
                q.push(tmp2); //入队以下次循环近一步搜索
            }
        }//for(i)
    }//while(empty)
}

int main()
{
    int startx, starty;
    //m行m列 注意题目先给出列数
    while (scanf("%d%d", &m, &n) == 2 && (m + n)){
        for (int i = 0; i < n; ++i){
            scanf("%s", mapp[i]);
            for (int j = 0; j < m; ++j){
                if (@ == mapp[i][j]){
                    startx = i;
                    starty = j;
                    cnt = 1; //初始化找到一块
                    mapp[i][j] = #; //访问过后为已访问过
                }
            }
        }//for(i)
        Node start;
        start.x = startx; start.y = starty;
        q.push(start);
        bfs();
        printf("%d\n", cnt);
    }

    return 0;
}
View Code

 

HDU 1312 ----- Red and Black 入门搜索 BFS解法

原文:http://www.cnblogs.com/tommychok/p/5020425.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!