poj 1979 Red and Black(BFS)

题意:在一个矩形房间里面被瓦片覆盖,分为白色的和红色的,白的可以走,红的不能走,起始位置在白色的瓦片上,可以上下左右移动;

".":白色的瓦片;

"#":红色的瓦片;

"@":起始位置;

计算可以移动到的白色瓦片的数量;

思路:bfs搜索,设一个变量sum记录,进队就自加;

代码如下:

#include <iostream>
#include <cstdio>
#include <memory.h>
#include <queue>
using namespace std;
char map_[25][25];
int w,h;
struct Node{
    int x,y;
};
int vis[25][25];
int ax[4] = {-1,0,1,0};
int ay[4] = {0,1,0,-1};
int BFS(Node no){
    queue<Node> mq;
    while(!mq.empty()){
        mq.pop();
    }
    mq.push(no);
    vis[no.x][no.y] = 1;
    int sum = 0;
    while(!mq.empty()){
        Node de = mq.front();
        mq.pop();
        sum++;
        for(int i=0;i<4;i++){
            Node d = de;
            d.x =de.x+ax[i];
            d.y =d.y+ay[i];
            if(vis[d.x][d.y]==0&&d.x>=0&&d.x<h&&d.y>=0&&d.y<w&&map_[d.x][d.y]=='.'){
                vis[d.x][d.y] = 1;
                mq.push(d);
            }
        }
    }
    return sum;
}


int main()
{
    while(~scanf("%d%d",&w,&h)){
        if(w==0&&h==0)return 0;
        int x,y;
        memset(map_,0,sizeof(map_));
        memset(vis,0,sizeof(vis));
        for(int i=0;i<h;i++){
            scanf("%s",map_[i]);
            for(int j=0;map_[i][j];j++){
                if(map_[i][j]=='@'){
                    x = i;
                    y = j;
                }
            }
        }
        Node no;
        no.x = x;no.y = y;
        int a = BFS(no);
        printf("%d
",a);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/hnzyyTl/p/4841706.html