【广度优先遍历BFS】HDU-1241 Oil Deposits

在这里插入图片描述
在这里插入图片描述

注解

1、从第一个点,到最后一个点,进行广度优先遍历BFS。
2、遍历八个方向:上下左右,右上,右下,左上,左下。

代码

#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

const int MAXN = 101;

int M, N;
int visit[MAXN][MAXN];
char ch[MAXN][MAXN];

int dirx[8] = {0, 0, 1, 1, 1, -1, -1, -1};
int diry[8] = {1, -1, 0, 1, -1, 0, 1, -1};

struct Node {
    int x;
    int y;
};

void BFS(int x, int y) {

    queue<Node> q;
    Node node;
    node.x = x;
    node.y = y;
    visit[x][y] = 1;
    q.push(node);

    while(q.size()>0) {
        Node top = q.front();
        q.pop();

        for(int i=0; i<8; i++) {
            int tmpX = top.x + dirx[i];
            int tmpY = top.y + diry[i];
            if(tmpX>=0 && tmpX<M && tmpY>=0 && tmpY<N && !visit[tmpX][tmpY] && ch[tmpX][tmpY]=='@') {
                visit[tmpX][tmpY] = 1;
                Node tmpNode;
                tmpNode.x = tmpX;
                tmpNode.y = tmpY;
                q.push(tmpNode);
            }
        }
    }

}


int main() {

    scanf("%d %d", &M, &N);
    getchar();
    while(M || N) {
        memset(visit, 0, sizeof(visit));
        memset(ch, 0, sizeof(ch));
        for(int i=0; i<M; i++) {
            for(int j=0; j<N+1; j++) {
                ch[i][j] = getchar();
            }
        }
        int cnt = 0;
        for(int i=0; i<M; i++) {
            for(int j=0; j<N; j++) {
                if(!visit[i][j] && ch[i][j]=='@') {
                    visit[i][j] = 1;
                    BFS(i, j);
                    cnt++;
                }
            }
        }
        printf("%d\n", cnt);
        scanf("%d %d", &M, &N);
        getchar();
    }

    return 0;
}

结果

在这里插入图片描述

发布了475 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/zhanggirlzhangboy/article/details/103792761