普及练习场 广度优先搜索 01迷宫

题目链接

题意理解

这题如果每次查询再去搜索能到多少个格子肯定是不行的,需要预处理一下,这是一个点。另外,要能想到,如果一个点能到另外一个点,那么这两个点最后能到的格子数是一样多的,这是第二个点。可能第二个点会想着去用并查集做,但是其实不需要,直接用flood_fill染色一下就好了。另外需要吐槽一下的是,我同样的代码用C++写就是全部AC,最慢的点是88ms,但是拿Java写就TLE了三个。。。

代码

#include <cstring>
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include <vector>

using namespace std;

const int maxn = 1010;
int n, m;
char mazes[maxn][maxn];
int colors[maxn][maxn];
int cell_nums[maxn * maxn];
int color = 0;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

void flood_fill(int x, int y) {
    if(colors[x][y] != -233) {
        return;
    }
    colors[x][y] = color;
    for(int i = 0; i < 4; i++) {
        int temp_x = x + dx[i];
        int temp_y = y + dy[i];
        if(temp_x < 0 || temp_x >= n) {
            continue;
        }
        if(temp_y < 0 || temp_y >= n) {
            continue;
        }
        if(mazes[x][y] != mazes[temp_x][temp_y]) {
            flood_fill(temp_x, temp_y);
        }
    }
}

int main() {
    scanf("%d %d", &n, &m);
    for(int i = 0; i < n; i++) {
        scanf("%s", mazes[i]);
    }
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            colors[i][j] = -233;
        }
    }
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            if(colors[i][j] == -233) {
                color++;
            }
            flood_fill(i, j);
        }
    }
    for(int i = 0; i < maxn * maxn; i++) {
        cell_nums[i] = 0;
    }
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            cell_nums[colors[i][j]]++;
        }
    }
    for(int i = 0; i < m; i++) {
        int x, y;
        scanf("%d %d", &x, &y);
        printf("%d\n", cell_nums[colors[x-1][y-1]]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值