TAG
- 芝士水题、算法 − 【搜索 − D F S 】、思维 − 【连通块】 芝士水题、算法 - 【搜索 - DFS】、思维 - 【连通块】 芝士水题、算法−【搜索−DFS】、思维−【连通块】时间复杂度
- O ( N 2 + M ) O(N^2 + M) O(N2+M)
//
#include <bits/stdc++.h>
using namespace std;
// #define int long long
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
const int N = 1111;
char g[N][N];
int n, m;
int save_idx[N][N];
int ans[N * N]; // 每个坐标都是一个单独的连通块
int idx, cnt;
void dfs(int x, int y, bool state) {
save_idx[x][y] = idx;
cnt++;
for (int i = 0; i < 4; i++) {
int tx = x + dx[i];
int ty = y + dy[i];
if (!(tx >= 1 && tx <= n && ty >= 1 && ty <= n)) continue;
if (save_idx[tx][ty]) continue;
if (g[x][y] == g[tx][ty]) continue;
dfs(tx, ty, g[tx][ty]);
}
}
void solve() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%s", g[i] + 1);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (save_idx[i][j] == 0) {
idx++;
cnt = 0;
dfs(i, j, g[i][j]);
ans[idx] = cnt;
}
}
}
while (m--) {
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", ans[save_idx[x][y]]);
}
}
signed main() {
int t = 1;
// scanf("%d", &t);
while (t--) solve();
return 0;
}
实现细节
空间复杂度能大别小
参考示意图
-
`
参考链接
- `
作者 | 乐意奥AI