codevs3410 别墅房间

题目描述 Description

小浣熊松松到他的朋友家别墅去玩,发现他朋友的家非常大,而且布局很奇怪。具体来说,朋友家的别墅可以被看做一个N*M的矩形,有墙壁的地方被标记为’#’,其他地方被标记为’.’。两个格子(a,b)和(c,d)被当做在同一个房间内,当且仅当|a-c|+|b-d|=1。现在松松想知道,有多少个房间。

输入描述  Input Description

第一行包含两个整数,N和M。

接下来N行描述别墅的情况,只包含’*’和’.’。

输出描述  Output Description

输出仅一行,为房间数。

样例输入  Sample Input

3 3

.#.

#.#

.#.

样例输出  Sample Output

5

数据范围及提示  Data Size & Hint

对于90%的数据,1<=N,M<=1000;

对于100%的数据,1<=N,M<=2000。

思路:

bfs求连通块

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>

using namespace std;
const int maxn = 2005;
int j[maxn][maxn],room[maxn][maxn];
long long int total = 0,m,n;
struct pos{
    int x;
    int y;
};
pos q[4000000];
pos dir[4];


int bfs(int y,int x){
    int h = 0,t = 0;
    q[0].y = y;
    q[0].x = x;
    int tx,ty;
    while(h <= t){
        
        int r3 = 0;
        for(r3 = 0;r3 <  4;r3++){
            x = q[h].x;
            y = q[h].y;
            tx = dir[r3].x;
            ty = dir[r3].y;
            if(y + ty >= 0 && y + ty < n && x + tx >= 0 && x + tx < m && room[y + ty][x + tx] && j[y + ty][x + tx]){
                t++;
                q[t].y = y + ty;
                q[t].x = x + tx;
                j[y + ty][x + tx] = 0;
                total--;
            }
        }
        h++ ;
    }
}

int main(){
    cin>>n>>m;
    dir[0].x = -1;dir[0].y = 0;
    dir[1].x = +1;dir[1].y = 0;
    dir[2].x = 0;dir[2].y = -1;
    dir[3].x = 0;dir[3].y = +1;
    char cmd;
    int r1 = 0,r2 = 0,temp = -1;
    for(r1 = 0;r1 < n;r1++){
        for(r2 = 0;r2 < m;r2++){
            cin>>cmd;
            if(cmd == '.') {
            j[r1][r2] = 1;
            room[r1][r2] = 1;
            total++;
        }else if(cmd == '#'){
            j[r1][r2] = 1;
            room[r1][r2] = 0;
        } 
        }
    }
    r1 = r2 =0;
    for(r1 = 0;r1 < n;r1++){
        for(r2 = 0;r2 < m;r2++){
            if(room[r1][r2] && j[r1][r2]){
                j[r1][r2] = 0;
                bfs(r1,r2);
            }

        }
    }
    cout<<total;
    return 0;
}

 

转载于:https://www.cnblogs.com/hyfer/p/5812547.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值