Igor In the Museum(bfs)

题目链接Codeforces 598D Igor In the Museum
说实话,在看别人博客之前,没看懂题。。
大意是这样的,用 ‘ * ’ 表示墙, ‘ . ’ 表示空地,空地四周的墙上都有画,然后随机给出一个空地坐标,问该 空地 和其连体的 空地 周围一共有多少画。

分析:
就是求出每个点周围有多少画,然后相加,但是因为是求一片空地的,所以不能用单点的坐标去记录画的数量,所以采用一维数组,讲每一片空地进行标号,最后不论输入的是这片空地的哪一块地,都直接输出该标号所代表空地的值,因为一片空地的标号所对应的值就是这块地上每一个点所及其连体地上的画的值,详细的看代码。

#include <iostream>
#include <cstring>
#include <string>
#include <queue>

using namespace std;

const int maxn = 1e3 + 10;

string maps[maxn];
int vis[maxn][maxn],r[maxn * maxn];//r表示每片空地标号所对应的画的值
int dir[4][2] = {{1,0},{-1,0},{0,-1},{0,1}},cnt;
int n,m,k;

struct node
{
    int x;
    int y;
};

bool if_fair(int x,int y)
{
    if(x >= 0&&y >= 0&&x < n&&y < m){
        return true;
    }
    return false;
}

void bfs(int x,int y)
{
    queue <node> q;
    node temp,now;
    now.x = x,now.y = y;
    q.push(now);
    int ans = 0;
    vis[x][y] = cnt;
    while(!q.empty()){
        temp = q.front();
        q.pop();
        ans += 4;
        for(int i = 0; i < 4; i++){
            now.x = temp.x + dir[i][0];
            now.y = temp.y + dir[i][1];
            if(if_fair(now.x,now.y)){
                if(maps[now.x][now.y] == '.'){
                    ans--;
                    if(!vis[now.x][now.y]){
                        /*因为联通的空地不管输入那一块空地坐标,都是输出这一片地的值,所以,把
                        这些相联通的空地都用一片空地的标号标记*/
                        vis[now.x][now.y] = cnt;
                        q.push(now);
                    }
                }
            }
            else{
                ans--;
            }
        }
    }
    r[cnt] = ans;
}

int main()
{
    while(cin>>n>>m>>k){
        for(int i = 0; i < n; i++){
            cin>>maps[i];
        }
        memset(vis,0,sizeof(vis));
        memset(r,0,sizeof(r));
        cnt = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < maps[i].size(); j++){
                if(maps[i][j] == '.'&&!vis[i][j]){
                    //每个点所对应一片空地的标号
                    cnt++;
                    bfs(i,j);
                }
            }
        }
        while(k--){
            int x,y;
            cin>>x>>y;
            x--,y--;
            cout<<r[vis[x][y]]<<endl;
        }
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值