zoukankan      html  css  js  c++  java
  • hdoj1421(bfs)

    bfs 练习题,简单bfs

    题意:给一块地图,找出油田的块的数量,这里要考虑油田的八个方向,上下左右(左右)上(左右)下,存在则可以并在一起。@是油田,*是土地,m是行,n是列。

    解题思路:用一个二维数组表示8个方向,然后bfs即可。

    #include <iostream>
    #include <cstdio>
    #include <queue>
    #include <cstring>
    using namespace std;
    
    const int M = 105;
    char map[M][M];int m,n;
    int res;
    struct Oil
    {
        int x,y;
    };
    queue <Oil> oil;
    int dire[8][2] = {{-1,0},{0,1},{1,0},{0,-1},{1,1},{-1,-1},{1,-1},{-1,1}};    //方向
    void bfs()
    {
        while (!oil.empty())
        {
            Oil oo = oil.front();
            oil.pop();
            int dx = oo.x;
            int dy = oo.y;
            for (int i = 0; i < 8; i++)
            {
                int x = dx+dire[i][0];
                int y = dy+dire[i][1];
                if (x >= 0 && x < m && y < n && y >= 0 && map[x][y] == '@')
                {
                    map[x][y] = '*';
                    Oil o;
                    o.x = x;
                    o.y = y;                
                    oil.push(o);
                }
            }
        }
    }
    int main()
    {
        while (cin >> m >> n && m)
        {
            res = 0;
            memset(visited,0,sizeof (visited));
            for (int i = 0;i < m;i++)
                for (int j = 0;j < n;j++)
                    cin >> map[i][j];
            for (int j = 0; j < m; j++)
            {
                for (int k = 0; k < n; k++)
                {
                    if (map[j][k] == '@')
                    {
                        map[j][k] = '*';
                        Oil oo;
                        oo.x = j;
                        oo.y = k;
                        oil.push(oo);
                        res++;
                        bfs();                    
                    }
                }
            }
            cout << res << endl;
        }
        return 0;
    }
  • 相关阅读:
    Android四大组件
    git命令记录
    .net core试水
    记一次NPOI的使用
    上位机开发经验教训总结
    Python爬虫,爬取腾讯漫画实战
    记一次微信小程序的开发
    sql使用cte表达式进行递归查询
    使用百度的webuploader进行附件上传
    Winform文件上传
  • 原文地址:https://www.cnblogs.com/ediszhao/p/4738769.html
Copyright © 2011-2022 走看看