25.Avoid The Lakes-dfs

本文介绍了一种使用深度优先搜索(DFS)算法解决农场洪水模拟问题的方法,旨在找出因洪水形成的最大湖泊覆盖的格子数量。通过构建网格地图并标记被水淹没的区域,该算法能够有效地确定最大的连续水域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Farmer John's farm was flooded in the most recent storm, a fact only aggravated by the information that his cows are deathly afraid of water. His insurance agency will only repay him, however, an amount depending on the size of the largest "lake" on his farm.

The farm is represented as a rectangular grid with N (1 ≤ N ≤ 100) rows and M (1 ≤ M ≤ 100) columns. Each cell in the grid is either dry or submerged, and exactly K (1 ≤ KN × M) of the cells are submerged. As one would expect, a lake has a central cell to which other cells connect by sharing a long edge (not a corner). Any cell that shares a long edge with the central cell or shares a long edge with any connected cell becomes a connected cell and is part of the lake.

输入:

<p>* Line 1: Three space-separated integers: <i>N</i>, <i>M</i>, and <i>K</i><br>* Lines 2..<i>K</i>+1: Line <i>i</i>+1 describes one submerged location with two space separated integers that are its row and column: <i>R</i> and <i>C</i></p>

输出:

<p>* Line 1: The number of cells that the largest lake contains. </p>

样例:

3 4 5
3 2
2 2
3 1
2 3
1 1


4

题目大意:Farm Jhon的农场被水淹了,他的农场是N*M个格子,现在其中有的格子里面有水,有的没有,如果两个有水的格子共用的一条边,则他们就是连通的,让求最大的有水连通面积。

思路:dfs

1.因为只有一个角公用的是不算连通的,所以有4个方向。

2.farm数组:没水用0表示,有水用-1表示,已经搜过的地方用1表示。

求最大的就行了

代码:

#include<iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define maxx 105
using namespace std;

int farm[maxx][maxx];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; //四个方向
int m,n,k,cnt;

void dfs(int x,int y)
{
    farm[x][y]=1;
    cnt++;
    for(int i=0;i<4;i++)
    {
        int next_x=x+dir[i][0];
        int next_y=y+dir[i][1];
        if(1<=next_x&&next_x<=n&&1<=next_y&&next_y<=m&&farm[next_x][next_y]==-1) //不越界保证有水
            dfs(next_x,next_y);
    }
}

int main()
{
    int x,y;
    int ans;
    cin>>n>>m>>k;
    memset(farm,0,sizeof(farm));
    ans=0;
    for(int i=0;i<k;i++)
    {
        cin>>x>>y;
        farm[x][y]=-1;///表示有水
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            cnt=0;
            if(farm[i][j]==-1)
            {
                dfs(i,j);
                ans=max(ans,cnt);
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值