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;
    }
    
  • 相关阅读:
    程序经理_产品经理_项目经理
    github上排名靠前的java项目之_storm
    垂直型与水平型电子商务网站的理解
    关于驱动更新的一点学习
    Balanced Binary Tree
    Gray Code
    Best Time to Buy and Sell Stock II
    Best Time to Buy and Sell Stock
    Maximum Depth of Binary Tree
    Next Permutation
  • 原文地址:https://www.cnblogs.com/littlehb/p/15069792.html
Copyright © 2011-2022 走看看