From 9eb819e3be9d75b2311837911594ee646e17954d Mon Sep 17 00:00:00 2001 From: Allen Guo Date: Sun, 21 Jul 2024 15:34:30 -0700 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200106.=E5=B2=9B=E5=B1=BF?= =?UTF-8?q?=E7=9A=84=E5=91=A8=E9=95=BF=20Java=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0106.岛屿的周长.md | 57 +++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/problems/kamacoder/0106.岛屿的周长.md b/problems/kamacoder/0106.岛屿的周长.md index 48400a95..6f3462c5 100644 --- a/problems/kamacoder/0106.岛屿的周长.md +++ b/problems/kamacoder/0106.岛屿的周长.md @@ -157,7 +157,62 @@ int main() { ## 其他语言版本 -### Java +### Java +```Java +import java.util.*; + +public class Main { + // 每次遍历到1,探索其周围4个方向,并记录周长,最终合计 + // 声明全局变量,dirs表示4个方向 + static int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + // 统计每单个1的周长 + static int count; + + // 探索其周围4个方向,并记录周长 + public static void helper(int[][] grid, int x, int y) { + for (int[] dir : dirs) { + int nx = x + dir[0]; + int ny = y + dir[1]; + + // 遇到边界或者水,周长加一 + if (nx < 0 || nx >= grid.length || ny < 0 || ny >= grid[0].length + || grid[nx][ny] == 0) { + count++; + } + } + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + // 接收输入 + int M = sc.nextInt(); + int N = sc.nextInt(); + + int[][] grid = new int[M][N]; + for (int i = 0; i < M; i++) { + for (int j = 0; j < N; j++) { + grid[i][j] = sc.nextInt(); + } + } + + int result = 0; // 总周长 + for (int i = 0; i < M; i++) { + for (int j = 0; j < N; j++) { + if (grid[i][j] == 1) { + count = 0; + helper(grid, i, j); + // 更新总周长 + result += count; + } + } + } + + // 打印结果 + System.out.println(result); + } +} +``` ### Python