1. 题目来源
链接:P1141 01迷宫
2. 题目解析
染色法和并查集是求连通块个数的两大方法,本题练习下搜索和染色法求连通块,算作是一个模板题,搜索写的少,出了各式各样的问题。
当然使用 flood fill
也是非常好的选择。
思路:
- 所有连通格子的答案是一样的,为连通块的格子总数。本题有多组询问,故可以每次求出一个连通块中的所有答案。当询问是新的连通块的时候,此时该位置答案没求出,则
bfs
去求该块所在连通块的格子数量。否则,当询问是已经求过的连通块时,则直接输出即可。 bfs
需要数组模拟队列,队列中的所有位置则是连通块的所有格子。队列空间需要开大,至少得装下整个二维数组,一开始在这WA
了两次…只开了一维,人傻了。连通块求得格子数,再将队列下标 [ 0 , t t ) [0, tt) [0,tt) 的格子统一赋值为所在连通块的格子数量,注意,一定是 [ 0 , t t ) [0, tt) [0,tt),又在这WA
了几次…tt
和hh
统一初始化为 0,hh < tt
说明队列不空。且入队、出队都使用的是后置++
,tt
最后会停留在一个无效位置,故队列中的所以有效元素是 [ 0 , t t ) [0,tt) [0,tt)。代码采用的是C++11
的写法,记得选择编译器选项。dfs
染色法求连通块应该是最为直观的。dfs
时给每一个连通点块都赋给它同一个颜色,每一个连通块都有不同的颜色,这样就能将二维数组的连通块染得花花绿绿,就能求解出答案了。dfs
暴力解法:针对每组询问,都直接dfs
找连通块即可,打个标记,每次找到一个没遍历过的点,且答案加一。思路正确,但是会t
三个点。因为处于同连通块的点虽然答案相同,但是仍然会做一遍dfs
这样就很慢了。- 可以仔细对比下染色法针对暴力
dfs
所作出的优化,体会其用途。
这个问题实质上是求单个连通块内的格子数量,并不等价于求解二维矩阵中连通块的个数!
至于连通块的个数也比较简单,也是 bfs
,但是得遍历所有的格子,判断其是否在连通块中,如果在,就消灭整个连通块,这个和寻找整个连通块完全等价的!遍历完毕记录答案即可~
bfs
求连通块格子数:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
const int N = 1005;
int n, m;
char g[N][N];
int st[N][N];
PII q[N * N]; // 一开始队列开小了,人傻了...
void bfs(int x, int y) {
int hh = 0, tt = 0; // hh == tt 时队列为空,tt 总是指向下一个需要放元素的位置,即最后的 tt 是没有有效元素的
int res = 1;
q[tt ++ ] = {x, y};
st[x][y] = 1;
while (hh < tt) {
auto t = q[hh ++ ];
for (int i = 0; i < 4; i ++ ) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a > 0 && a <= n && b > 0 && b <= n && !st[a][b] && (g[a][b] != g[t.x][t.y])) {
res ++;
q[tt ++ ] = {a, b};
st[a][b] = 1;
}
}
}
for (int i = 0; i < tt; i ++ ) st[q[i].x][q[i].y] = res; // 有效是 tt 个,tt 下标不是有效元素,写了个 i<=tt,人傻了...
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> g[i] + 1;
while (m -- ) {
int x, y;
cin >> x >> y;
if (st[x][y]) cout << st[x][y] << endl;
else {
bfs(x, y);
cout << st[x][y] << endl;
}
}
return 0;
}
dfs
染色法求连通块格子数:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1005;
int n, m, cnt = 1, res; // cnt 颜色初始化为 1,res 为连通块中格子的个数。全局变量传递信息,dfs 中常用的一种
char g[N][N];
int st[N][N];
int d[N * N];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void dfs(int x, int y) {
if (x < 1 || x > n || y < 1 || y > n || st[x][y]) return ;
res ++ ; // 记录连通格子数
st[x][y] = cnt; // 标记同色
for (int i = 0; i < 4; i ++ ) {
int a = x + dx[i], b = y + dy[i];
if (g[a][b] != g[x][y])
dfs(a, b);
}
d[cnt] = res;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> g[i] + 1;
while (m -- ) {
int x, y;
cin >> x >> y;
if (!st[x][y]) {
res = 0; // 注意初始化
dfs(x, y);
cnt ++ ;
}
cout << d[st[x][y]] << endl;
}
return 0;
}