From ad3aecc7f3d8f5033bcacce86d68a2a420893f1c Mon Sep 17 00:00:00 2001 From: xsduan98 Date: Sun, 12 Sep 2021 20:53:53 +0800 Subject: [PATCH] =?UTF-8?q?463.=E5=B2=9B=E5=B1=BF=E7=9A=84=E5=91=A8?= =?UTF-8?q?=E9=95=BF=20=E6=B7=BB=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0463.岛屿的周长.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0463.岛屿的周长.md b/problems/0463.岛屿的周长.md index 18654758..609c25a5 100644 --- a/problems/0463.岛屿的周长.md +++ b/problems/0463.岛屿的周长.md @@ -84,6 +84,37 @@ public: Java: +```java +// 解法一 +class Solution { + // 上下左右 4 个方向 + int[] dirx = {-1, 1, 0, 0}; + int[] diry = {0, 0, -1, 1}; + + public int islandPerimeter(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + int res = 0; // 岛屿周长 + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + for (int k = 0; k < 4; k++) { + int x = i + dirx[k]; + int y = j + diry[k]; + // 当前位置是陆地,并且从当前位置4个方向扩展的“新位置”是“水域”或“新位置“越界,则会为周长贡献一条边 + if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0) { + res++; + continue; + } + } + } + } + } + return res; + } +} +``` + Python: Go: