From 03cf40e1034f553873e0393e6bf2b1aaaa39242a Mon Sep 17 00:00:00 2001 From: zouwx2cs Date: Tue, 16 Oct 2018 20:57:12 +0800 Subject: [PATCH] 695.Max Area of Island cpp version(16 ms) --- solution/695.Max Area of Island/README.md | 35 ++++++++++++++ solution/695.Max Area of Island/Solution.cpp | 51 ++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 solution/695.Max Area of Island/README.md create mode 100644 solution/695.Max Area of Island/Solution.cpp diff --git a/solution/695.Max Area of Island/README.md b/solution/695.Max Area of Island/README.md new file mode 100644 index 0000000000000..4c77c4ed6ce52 --- /dev/null +++ b/solution/695.Max Area of Island/README.md @@ -0,0 +1,35 @@ +## 岛屿的最大面积 +### 题目描述 + +给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。 + +找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。) + +示例 1: +``` +[[0,0,1,0,0,0,0,1,0,0,0,0,0], + [0,0,0,0,0,0,0,1,1,1,0,0,0], + [0,1,1,0,1,0,0,0,0,0,0,0,0], + [0,1,0,0,1,1,0,0,1,0,1,0,0], + [0,1,0,0,1,1,0,0,1,1,1,0,0], + [0,0,0,0,0,0,0,0,0,0,1,0,0], + [0,0,0,0,0,0,0,1,1,1,0,0,0], + [0,0,0,0,0,0,0,1,1,0,0,0,0]] + +对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。 +``` + +示例 2: +``` +[[0,0,0,0,0,0,0,0]] + +对于上面这个给定的矩阵, 返回 0。 + +注意: 给定的矩阵grid 的长度和宽度都不超过 50。 +``` + +### 解法 +搜索 + +``` +``` \ No newline at end of file diff --git a/solution/695.Max Area of Island/Solution.cpp b/solution/695.Max Area of Island/Solution.cpp new file mode 100644 index 0000000000000..6cc0a68f4216c --- /dev/null +++ b/solution/695.Max Area of Island/Solution.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + bool v[55][55] = {0, } ; // ʱ + int maxAreaOfIsland(vector>& grid) + { + int maxAera = 0 ; + for (int i = 0; i < grid.size(); ++i) + { + if (0 == grid.size()) + { + return 0 ; + } + + for (int j = 0; j < grid[0].size(); ++j) + { + if (1 == grid[i][j] && !v[i][j]) + { + int cnt = calcAera(grid, i, j) ; + if (cnt > maxAera) + maxAera = cnt ; + } + } + } + return maxAera ; + } + + int calcAera(vector>& grid, int i, int j) + { + if (i < 0 || i >= grid.size()) + return 0 ; + if (j < 0 || j >= grid[0].size()) + return 0 ; + + if (v[i][j]) + return 0 ; + + v[i][j] = true ; + + + if (grid[i][j]) + { + return 1 + + calcAera(grid, i-1, j) + + calcAera(grid, i+1, j) + + calcAera(grid, i, j-1) + + calcAera(grid, i, j+1) ; + } + else + return 0 ; + } +} ; \ No newline at end of file