您的位置:首页 > 其它

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

2018-01-03 20:22 260 查看
题目链接

题意理解

这题如果每次查询再去搜索能到多少个格子肯定是不行的,需要预处理一下,这是一个点。另外,要能想到,如果一个点能到另外一个点,那么这两个点最后能到的格子数是一样多的,这是第二个点。可能第二个点会想着去用并查集做,但是其实不需要,直接用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: