P1596 Lake CountingS

点击查看代码
#include <iostream>
#include <queue>
#include <vector>

using namespace std;


const int MAXN = 105;

int N, M;
char grid[MAXN][MAXN];  // 存地图
bool vis[MAXN][MAXN];   // 存是否访问过

//方向数组
int dx[8] = {-1, -1, -1,  0, 0,  1, 1, 1};
int dy[8] = {-1,  0,  1, -1, 1, -1, 0, 1};

//bfs将同一个水坑中的所有元素都标记为true
void bfs(int startX, int startY) {
    //1.初始化和启动
    queue<pair<int, int>> q;
    q.push({startX, startY});
    vis[startX][startY] = true;

    //2.开始循环
    while (!q.empty()) {
        //取出队头
        pair<int, int> curr = q.front();
        q.pop();
        
        int x = curr.first;
        int y = curr.second;
        
        // 观察邻居
        for (int i = 0; i < 8; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            
            // 判断与选择
            if (nx >= 0 && nx < N && ny >= 0 && ny < M) {
                if (grid[nx][ny] == 'W' && !vis[nx][ny]) {
                    vis[nx][ny] = true; //标记
                    q.push({nx, ny});
                }
            }
        }
    }
}

int main() {
    // 读入优化
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    cin >> N >> M;
    
    // 读入地图
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            cin >> grid[i][j];
            vis[i][j] = false; // 初始化所有点都没访问过
        }
    }
    
    int ans = 0; // 记录水坑数量
    
   //双重循环扫描全图
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            //找到了水并且还未被标记过,然后就用bfs把这一块全部扫描
            if (grid[i][j] == 'W' && !vis[i][j]) {
                ans++;       
                bfs(i, j);   
            }
        }
    }
    
    cout << ans << endl;
    
    return 0;
}
posted @ 2026-01-10 16:11  AnoSky  阅读(2)  评论(0)    收藏  举报