UVA572 油田 Oil Deposits(BFS复习)

#include <iostream>
#include <set>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define ll long long
using namespace std;
const int M = 1e3 + 1;
char a[M][M];
int n, m;
queue<int> v, u;
bool check(int x, int y) {
    return x >= 1 && x <= n && y >= 1 && y <= m;
}
inline void dfs(int x, int y) {
    a[x][y]='*';//本来想开个vis二维数组存储这个点是否走过,但是直接把原图变一下,更快
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
            if (i == j && i == 0) continue;
            int dx = x + i;
            int dy = y + j;
            if (check(dx,dy) && vis[dx][dy] == 0&&a[dx][dy]=='@') {
                dfs(dx,dy);//直接搜索下一个点就好,这里别记错了
                
            }
        }
    }
}
int main()
{
    while (scanf("%d %d", &n, &m) != EOF) {
        
        getchar();
        if (n == 0 && m == 0) break;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                cin >> a[i][j];
            }
            getchar();
        }

        int ans = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (a[i][j] == '@') {
                    v.push(i);
                    u.push(j);
                    while (!v.empty()) {
                        dfs(v.front(), u.front());
                        v.pop();
                        u.pop();
                    }
                    ans++;
                }
            }
            
        }
        cout<<ans<<endl;
    }
}

 

上一篇:opencv 图像处理(五)边缘、角检测


下一篇:连通块的实现油田连通块的实现;第一行输入n,m,代表油田地的大小;接下来的n行,每行输入m个字符;最后一行输出油田的数量