友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

200. Number of Islands

Given a 2d grid map of ’1'`s (land) and ’0'`s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

思路分析

0200 01
0200 02

思考题:看题解可以使用 UnionFind 来解决这个问题。可以思考一下,如何实现?

这道题与 0130-surrounded-regions.adoc 类似。

  • 一刷

  • 二刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * Runtime: 1 ms, faster than 99.99% of Java online submissions for Number of Islands.
 *
 * Memory Usage: 42 MB, less than 41.86% of Java online submissions for Number of Islands.
 *
 * Copy from: https://leetcode-cn.com/problems/number-of-islands/solution/dao-yu-shu-liang-by-leetcode/[岛屿数量 - 岛屿数量 - 力扣(LeetCode)]
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2020-01-25 23:42
 */
public int numIslands(char[][] grid) {
    if (Objects.isNull(grid) || grid.length == 0) {
        return 0;
    }
    int yLength = grid.length;
    int xLength = grid[0].length;
    int result = 0;
    for (int y = 0; y < yLength; y++) {
        for (int x = 0; x < xLength; x++) {
            if (grid[y][x] == '1') {
                result++;
                dfs(grid, y, x);
            }
        }
    }

    return result;
}

private void dfs(char[][] grid, int y, int x) {
    int yLength = grid.length;
    int xLength = grid[0].length;
    if (y < 0 || y >= yLength || x < 0 || x >= xLength
            || grid[y][x] == '0') {
        return;
    }
    grid[y][x] = '0';
    dfs(grid, y - 1, x);
    dfs(grid, y + 1, x);
    dfs(grid, y, x - 1);
    dfs(grid, y, x + 1);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-07-11 20:04:34
 */
public int numIslands(char[][] grid) {
  if (grid == null || grid.length == 0 || grid[0].length == 0) {
    return 0;
  }
  int result = 0;
  for (int i = 0; i < grid.length; i++) {
    for (int j = 0; j < grid[i].length; j++) {
      if (grid[i][j] == '1') {
        result++;
        dfs(grid, i, j);
      }
    }
  }
  return result;
}

private void dfs(char[][] grid, int row, int col) {
  if (row < 0 || grid.length <= row
    || col < 0 || grid[0].length <= col) {
    return;
  }
  if (grid[row][col] == '0' || grid[row][col] != '1') {
    return;
  }
  grid[row][col] = '2';
  dfs(grid, row - 1, col);// 上
  dfs(grid, row + 1, col);// 下
  dfs(grid, row, col - 1); // 左
  dfs(grid, row, col + 1); // 右
}