假设有二维数组元素为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; }