洛谷P1454 圣诞夜的极光 题解 搜索入门

题目链接:https://www.luogu.com.cn/problem/P1454

题目大意:连通块问题。

解题思路:搜索。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
int n, m, cnt;
char maze[maxn][maxn];
inline bool in_map(int x, int y) {
    return x >= 0 && x < n && y >= 0 && y < m;
}
void dfs(int x, int y) {
    maze[x][y] = '-';
    for (int i = -2; i <= 2; i ++) {
        for (int j = -2; j <= 2; j ++) {
            int xx = x + i, yy = y + j;
            if (abs(i) + abs(j) <= 2 && in_map(xx, yy) && maze[xx][yy] == '#')
                dfs(xx, yy);
        }
    }
}
int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i ++) scanf("%s", maze[i]);
    for (int i = 0; i < n; i ++) {
        for (int j = 0; j < m; j ++) {
            if (maze[i][j] == '#') {
                cnt ++;
                dfs(i, j);
            }
        }
    }
    printf("%d\n", cnt);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/quanjun/p/12240419.html
今日推荐