题目地址:
https://www.acwing.com/problem/content/1099/
给定一个
M
×
N
M\times N
M×N的char二维矩阵,求里面的'W'
八连通块有多少个。
输入格式:
第一行包含两个整数
M
M
M和
N
N
N。接下来
M
M
M行,每行包含
N
N
N个字符,字符为”W”或”.”,字符之间没有空格。
输出格式:
输出一个整数,表示连通块数目。
数据范围:
1
≤
N
,
M
≤
1000
1\le N,M\le 1000
1≤N,M≤1000
法1:DFS。直接把每个'W'
连通块全标记掉即可。代码如下:
#include <iostream>
using namespace std;
const int N = 1010;
char a[N][N];
int m, n;
int res;
void dfs(int x, int y) {
a[x][y] = '.';
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++) {
int nx = x + dx, ny = y + dy;
if (1 <= nx && nx <= m && 1 <= ny && ny <= n && a[nx][ny] == 'W')
dfs(nx, ny);
}
}
int main() {
cin >> m >> n;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
cin >> a[i][j];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (a[i][j] == 'W') {
dfs(i, j);
res++;
}
cout << res << endl;
return 0;
}
时间复杂度 O ( M N ) O(MN) O(MN),空间 O ( 1 ) O(1) O(1)。
法2:BFS。思路一样。代码如下:
#include <iostream>
#include <queue>
using namespace std;
const int N = 1010;
char a[N][N];
int m, n;
int res;
queue<pair<int, int> > q;
void bfs(int x, int y) {
a[x][y] = '.';
q.push({x, y});
while (!q.empty()) {
x = q.front().first, y = q.front().second;
q.pop();
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++) {
int nx = x + dx, ny = y + dy;
if (1 <= nx && nx <= m && 1 <= ny && ny <= n && a[nx][ny] == 'W') {
q.push({nx, ny});
a[nx][ny] = '.';
}
}
}
}
int main() {
cin >> m >> n;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
cin >> a[i][j];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (a[i][j] == 'W') {
bfs(i, j);
res++;
}
cout << res << endl;
return 0;
}
时空复杂度一样。