1 solutions

  • 1
    @ 2025-7-28 17:24:03

    #include <bits/stdc++.h> using namespace std;

    char mapp[105][105]; int n, m, ans; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0};

    struct place { int a, b; };

    void bfs(int x, int y) { queue<place> q; mapp[x][y] = '0'; // 将搜索过的点标记为障碍 q.push({x, y});

    while (q.size()>0) {
        place xy = q.front(); // 取出队头
        q.pop();
        
        for (int i = 0; i < 4; i++) {
            int x1 = xy.a + dx[i],y1 = xy.b + dy[i];
            
            if (x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= m && mapp[x1][y1] != '0') {
                q.push({x1, y1});
                mapp[x1][y1] = '0'; // 标记为已访问
            }
        }
    }
    

    }

    int main() { cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> mapp[i][j]; } }

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (mapp[i][j] != '0') {
                bfs(i, j);
                ans++;
            }
        }
    }
    
    cout << ans;
    return 0;
    

    }

    • 1

    Information

    ID
    456
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    7
    Tags
    (None)
    # Submissions
    23
    Accepted
    9
    Uploaded By