BFS习题

hdu 1312题

题意:在一个长方形房间内,一个人站在’@‘上可执行上下左右的操作,’#‘相当于墙壁,’.'为地板,问最多可以走多少个地板

思路:BFS(广度优先搜索),遍历所有‘.’;

#include<iostream>
#include<queue>
using namespace std;


char arr[23][23];
int num, W, H;
//上下左右行走
int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

struct node {
    int x, y;
};
//判断是否越界
#define CHECK(x,y) (x < H && y < W && x >= 0 && y >= 0)

void BFS(int dx, int dy) {
    queue<node>q;
    node start, next;
    num = 1 ;
    start.x = dx, start.y = dy;
    q.push(start);
    while(!q.empty()) {
        start = q.front();
        q.pop();
       // cout<<"out:"<<start.x<<start.y<<endl;
        for(int i = 0; i < 4; i++) {
            next.x = start.x + dir[i][0];
            next.y = start.y + dir[i][1];
            if(CHECK(next.x, next.y) && arr[next.x][next.y] == '.') {
                num++;
                arr[next.x][next.y] = '#';
                q.push(next);
            }

        }

    }
}
int main() {
    int dx, dy;
    while(cin >> W >> H) {
        if(W == 0 && H == 0)
            break;
        for(int i = 0; i < H; i++)
            for(int j = 0; j < W; j++) {
                cin >> arr[i][j];
                if(arr[i][j] == '@')
                    dx = i, dy = j;
            }
            num = 0;
            BFS(dx, dy);
          cout << num << endl;
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值