zoukankan      html  css  js  c++  java
  • P1596 湖计数题解

    题目传送门

    一、广度优先搜索解法

    #include <bits/stdc++.h>
    
    using namespace std;
    const int N = 110;
    char a[N][N]; //地图
    
    //坐标结构体
    struct coord {
        int x, y;
    };
    int n, m;
    int cnt;      //目前的水坑数
    
    //八个方向
    int dx[8] = {0, 0, -1, 1, -1, 1, -1, 1};
    int dy[8] = {1, -1, 0, 0, -1, -1, 1, 1};
    
    //广度优先搜索
    void bfs(int x, int y) {
        //队列
        queue<coord> q;
        q.push({x, y});
        while (!q.empty()) {
            //队列头
            auto p = q.front();
            q.pop();
            //修改为.,防止再次更新
            a[p.x][p.y] = '.';
    
            //尝试八个方向
            for (int k = 0; k < 8; k++) {
                int x1 = p.x + dx[k], y1 = p.y + dy[k];//目标点坐标
                if (x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= m && a[x1][y1] == 'W')
                    q.push({x1, y1});
            }
        }
    }
    
    int main() {
        //输入
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                cin >> a[i][j];
    
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                //发现水坑
                if (a[i][j] == 'W') {
                    //开始进行广度搜索
                    bfs(i, j);
                    //这个cnt++妙的很
                    cnt++;
                }
        cout << cnt << endl;
        return 0;
    }
    

    2、深度优先算法

    #include <bits/stdc++.h>
    
    using namespace std;
    const int N = 110;
    int n, m;
    char a[N][N]; //地图
    int cnt;      //目前的水坑数
    //八个方向
    int dx[8] = {0, 0, -1, 1, -1, 1, -1, 1};
    int dy[8] = {1, -1, 0, 0, -1, -1, 1, 1};
    
    void dfs(int x, int y) {
        //修改为.,防止再次更新
        a[x][y] = '.';
        //尝试八个方向
        for (int k = 0; k < 8; k++) {
            int x1 = x + dx[k], y1 = y + dy[k];//目标点坐标
            if (x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= m && a[x1][y1] == 'W')
                dfs(x1, y1);
        }
    }
    
    int main() {
        //输入
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                cin >> a[i][j];
    
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                //发现水坑
                if (a[i][j] == 'W') {
                    dfs(i, j);
                    //这个cnt++妙的很
                    cnt++;
                }
        cout << cnt << endl;
        return 0;
    }
    
  • 相关阅读:
    linux下LD_PRELOAD的用处
    三个通用的脚本,处理MySQL WorkBench导出表的JSON数据进SQLITE3
    ubuntu 18.04下,KMS_6.9.1服务器启动后,客户端连接一段时间因为libnice而crash的问题修复
    Daliy Algorithm(线段树&组合数学) -- day 53
    Daliy Algorithm(链表&搜索&剪枝) -- day 52
    Daliy Algorithm(二分&前缀和) -- day 51
    每日算法
    动态规划--01背包模型
    每日算法
    每日算法
  • 原文地址:https://www.cnblogs.com/littlehb/p/15069792.html
Copyright © 2011-2022 走看看