• c++ Lake Counting


    Lake Counting(bfs dfs)

    题目描述

    样例输入

    10 12
    W . . . . . . . . W W .
    . W W W . . . . . W W W
    . . . . W W . . . W W .
    . . . . . . . . . W W .
    . . . . . . . . . W . .
    . . W . . . . . . W . .
    . W . W . . . . . W W .
    W . W . W . . . . . W .
    . W . W . . . . . . W .
    . . W . . . . . . . W .
    

    样例输出

    3
    

    dfs代码

    #include <stdio.h>//includes
    #include <iostream>//up
    using namespace std;//
    int N, M;//定义行,列
    char field[101][101];//整个院子(矩阵)
    void dfs(int x,int y)//dfs
    {
        field[x][y] = '.';//标为没有积水
        for (int dx = -1; dx <= 1; dx++)//枚举x坐标
        {//循环遍历8个方向
            for (int dy = -1; dy <= 1; dy++)//枚举x坐标
            {
                int nx = x + dx, ny = y + dy;//移动到遍历的方向
                if (0 <= nx && nx < N && 0 <= ny && ny < M&&field[nx][ny] == 'W')//判断是否穿墙 并且有积水
                    dfs(nx, ny);//递归搜索下一个积水
            }
        }
        return;//退出
    }
    
    void solve()//solve基本输入 调用函数 
    {
        int res = 0;//计数器
        for (int i = 0;i < N;i ++)//输入
        {
            for (int j = 0;j < M;j ++)//up
            {
                cin >> field[i][j];//up
            }
        }
        for (int i = 0; i < N; i++) //查找第一处积水
        {
            for (int j = 0; j < M; j++) //up
            {
                if (field[i][j] == 'W') //如果有积水
                {
                    dfs(i, j);//调用函数递归查找所有节点
                    res++;//计数器 + 1
                }
            }
        }
        printf("%d", res);//打印结果 Print res
    }
    
    int main() //main
    {
        scanf("%d%d", &N,&M);//输入行和列
        solve();//调用solve
       // system("pause");
        return 0;//return
    }
    
    
  • 相关阅读:
    C struct 中字节对齐问题(转)
    蚁群算法,PSO算法以及两种算法可以融合的几种方法
    遗传及蚁群算法
    ListBox FAQ常用问题
    关于C#中ListBox控件重绘Item项
    创业艰难,问题多多
    asp.net客户端脚本验证小技巧
    防止ASP.NET按钮多次提交的办法
    鼠标点到文本框时的提示信息
    枚举的转换
  • 原文地址:https://www.cnblogs.com/LJA001162/p/11278259.html
Copyright © 2020-2023  润新知