Avoid The Lakes(DFS)

Description
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 ≤ K ≤ N × 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.

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

Output
* Line 1: The number of cells that the largest lake contains. 

Sample Input
3 4 5
3 2
2 2
3 1
2 3
1 1
Sample Output
4

题意:奶牛怕水,第一行输入一个N*M行大的矩阵格,接下来已知K个方格里有水,接下来K行就是有水的格子,从1~N行,1~M列
如果有水的格子左右或者上下相连视为连接,问最多有几个水塘连在一起
题解:按照两个循环将所有格子都走一遍,遇到一个格子有水则dfs,把相连的全都计数,记录相连的数量,再继续循环,看有没有没有计过数的水格,再一次dfs计数,走遍所有格子后比较计数大小,输出最大值

代码(C)

#include<stdio.h>
#include<string.h>
int a[105][105],ans,m,n;
int b[4][2]={{0,1},{0,-1},{1,0},{-1,0}};

void dfs(int q,int p)
{
    ans=ans+1;//每找到一个计数加一
    a[q][p]=0;//计数后将这个格子标记
    for(int i=0;i<4;i++)
    {
        int x=q+b[i][0];
        int y=p+b[i][1];
        if(q<=n&&p<=m&&q>0&&p>0&&a[x][y]==1)
          dfs(x,y);
    }
    return;
}

int main()
{
    int k,x,y,max;
    while(scanf("%d%d%d",&n,&m,&k)!=EOF)
    {
        memset(a,0,sizeof(a));//清空数组计数
        for(int i=0;i<k;i++)
        {
            scanf("%d%d",&x,&y);
            a[x][y]=1;
        }
        max=0;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                if(a[i][j]==1)//找到一个有水的格子
                {
                    ans=0;
                    dfs(i,j);
                    if(ans>max)  max=ans;
                }
            }
        }
        printf("%d\n",max);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值