From 6a201720030faa7a70abcc313c1aa756245f3329 Mon Sep 17 00:00:00 2001 From: AronJudge <2286381138@qq.com> Date: Sat, 20 Aug 2022 10:38:58 +0800 Subject: [PATCH] =?UTF-8?q?463=20=E5=B2=9B=E5=B1=BF=E7=9A=84=E5=91=A8?= =?UTF-8?q?=E9=95=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新Java的方法二 --- problems/0463.岛屿的周长.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0463.岛屿的周长.md b/problems/0463.岛屿的周长.md index ea038140..3dc69f20 100644 --- a/problems/0463.岛屿的周长.md +++ b/problems/0463.岛屿的周长.md @@ -118,6 +118,27 @@ class Solution { return res; } } + +// 解法二 +class Solution { + public int islandPerimeter(int[][] grid) { + // 计算岛屿的周长 + // 方法二 : 遇到相邻的陆地总周长就-2 + int landSum = 0; // 陆地数量 + int cover = 0; // 相邻陆地数量 + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1) { + landSum++; + // 统计上面和左边的相邻陆地 + if(i - 1 >= 0 && grid[i-1][j] == 1) cover++; + if(j - 1 >= 0 && grid[i][j-1] == 1) cover++; + } + } + } + return landSum * 4 - cover * 2; + } +} ``` Python: