找出面积最大的土地

假设有二维数组元素为L W L表示土地,W表示水域,使用DP找到面积最大的土地,每个单元的土地被视为1个单位,只能考查一块土地的上下左右的连续单元,不能考查斜线方向的。

Example:
LLLL
LLWL
LWLW
WWLL

上图答案为8.

Suppose you have given a 2D array having filled with "L" or "W" i.e. either land or water, using DP you have to find it largest land unit in this grid, each cell of land is considered as 1 unit and you can only consider up,down,left or right land units as contiguous to each other not diagonal unit.
Example:
LLLL
LLWL
LWLW
WWLL
in the above mentioned grid the answer will be 8 units

函数CountContiguous()用深度优先搜索,首先考查一个点是否为L,如果为L将其置为A,表示已考察过了,继续搜索邻接点。否则返回0,表示陆地为0.

函数Count_land()计算遍历考查每一块土地,如果为陆地,继续考查相邻节点。

时间复杂度为O(n^2).


#include <iostream>
using namespace std;
#define ROWS 4
#define  CLOS 4
int CountContiguous(char [ROWS][CLOS],int ,int );
int Count_land(char S[ROWS][CLOS])
{
	int count = 0;
	int result = 0;
	for (int i = 0;i<ROWS;i++)
	{
		for (int j = 0;j<CLOS;j++)
		{
			if (S[i][j] == 'L')
			{
				count = CountContiguous(S,i,j);
				if (count > result)
				{
					result = count;
				}
			}//if
		}//for 
	}//for
	return result;
}
int CountContiguous(char S[ROWS][CLOS],int x,int y)
{
	if (x<0||y<0||x>ROWS-1||y>CLOS-1||S[x][y] != 'L')
	{
		return 0;
	}
	S[x][y] = 'A';
	return 1+CountContiguous(S,x-1,y)+CountContiguous(S,x,y-1)+CountContiguous(S,x,y+1)+CountContiguous(S,x+1,y);
}
int main()
{
	char s[ROWS][CLOS] = {{'L', 'L', 'L', 'L'},
	{'L', 'L', 'W', 'L'},
	{'L', 'W', 'L', 'W'},
	{'W', 'W', 'L', 'L'}};
	cout<<Count_land(s);
	return 0;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值