zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    J2EE第四周
    J2EE 第三周
    jsf简单入门
    Applrt和Ajax
    hello.java分析
    filter用户例子
    分析LogFilter
    理解session
    关于XML
    企业级应用和互联网应用的区别
  • 原文地址:https://www.cnblogs.com/hyfer/p/5812547.html
Copyright © 2011-2022 走看看