【ACWing】1097. 池塘计数

题目地址:

https://www.acwing.com/problem/content/1099/

给定一个 M × N M\times N M×N的char二维矩阵,求里面的'W'八连通块有多少个。

数据范围:
1 ≤ N , M ≤ 1000 1\le N,M\le 1000 1N,M1000

思路是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)

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/113876744