POJ 2386

POJ 2386

BFS 求连通块

这题是八连通,注意别写错。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define endl '\n'
const int N = 200;
char g[N][N];
int n,m,ans;
int dx[8] = {0,0,1,-1,1,1,-1,-1};
int dy[8] = {1,-1,0,0,-1,1,-1,1};
struct node {
    int x,y;
};
void bfs(int x,int y) {
    queue<node> q;
    q.push({x,y});
    g[x][y] = '.';
    while(q.size()) {
        node t = q.front();
        q.pop();
        for(int i = 0;i < 8; ++i) {
            int nx = t.x + dx[i],ny = t.y + dy[i];
            if(nx >= 0 && nx < n && ny >= 0 && ny < m && g[nx][ny] == 'W' ) {
                q.push({nx,ny});
                g[nx][ny] = '.';
            }
        }
    }
}
int main() {
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin >> n >> m;
    for(int i = 0;i < n; ++i)
        for(int j = 0;j < m; ++j)
            cin >> g[i][j];
    for(int i = 0;i < n; ++i){
        for(int j = 0;j < m; ++j) {
            if(g[i][j] == 'W'){
                bfs(i,j);
                ans ++;
            }
        }
    }
    cout << ans << endl;
    return 0;
}
posted @ 2020-03-06 17:36  南风--  阅读(77)  评论(0编辑  收藏  举报