From 2fdfd0511556e0238237f5b3dc9e302cbb575fe8 Mon Sep 17 00:00:00 2001 From: Yuki Chen <826992207@qq.com> Date: Fri, 9 Sep 2022 20:39:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00200.=E5=B2=9B=E5=B1=BF?= =?UTF-8?q?=E6=95=B0=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 47 +++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index d43d6183..f70ea50c 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -144,3 +144,50 @@ public: }; ``` + +## 其他语言版本 + +### Java + +```java +class Solution { + + boolean[][] visited; + int[][] move = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + public int numIslands(char[][] grid) { + int res = 0; + visited = new boolean[grid.length][grid[0].length]; + for(int i = 0; i < grid.length; i++) { + for(int j = 0; j < grid[0].length; j++) { + if(!visited[i][j] && grid[i][j] == '1') { + bfs(grid, i, j); + res++; + } + } + } + return res; + } + + //将这片岛屿上的所有陆地都访问到 + public void bfs(char[][] grid, int y, int x) { + Deque queue = new ArrayDeque<>(); + queue.offer(new int[]{y, x}); + visited[y][x] = true; + while(!queue.isEmpty()) { + int[] cur = queue.poll(); + int m = cur[0]; + int n = cur[1]; + for(int i = 0; i < 4; i++) { + int nexty = m + move[i][0]; + int nextx = n + move[i][1]; + if(nextx < 0 || nexty == grid.length || nexty < 0 || nextx == grid[0].length) continue; + if(!visited[nexty][nextx] && grid[nexty][nextx] == '1') { + queue.offer(new int[]{nexty, nextx}); + visited[nexty][nextx] = true; //只要加入队列就标记为访问 + } + } + } + } +} +```