算法:求岛屿的数量200. Number of Islands

Posted 架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:求岛屿的数量200. Number of Islands相关的知识,希望对你有一定的参考价值。

200. Number of Islands

Given an m x n 2D binary grid grid which represents a map of '1’s (land) and '0’s (water), return 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: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is '0' or '1'.

1. 递归解法

2层循环遍历是否为’1’, 如果是,则递归循环打掉所有上下左右的的’1’. 再接着遍历。如果还能优化,可以记录遍历过的记录,直接跳过打掉过的1.

class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int k = 0; k < grid[0].length; k++) {
                if (grid[i][k] == '1') {
                    count++;
                    sink(grid, i, k);
                }
            }
        }
        return count;
    }
    
    private void sink(char[][] grid, int i, int k) {
        if (i < 0 || k < 0 || i >= grid.length || k >= grid[0].length || grid[i][k] == '0') return;
        grid[i][k] = '0';
        sink(grid, i+1, k);
        sink(grid, i, k+1);
        sink(grid, i-1, k);
        sink(grid, i, k-1);
    }
}

2. 递归求解,优化掉重复的sink函数

看到优雅的写法就是上下左右,用一个数组{0, 1, 0, -1, 0} 两两遍历,

  1. 0,1
  2. 1,0
  3. 0, -1
  4. -1, 0
class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int k = 0; k < grid[0].length; k++) {
                if (grid[i][k] == '1') {
                    count++;
                    sink(grid, i, k);
                }
            }
        }
        return count;
    }
    
    int[] d = {0, 1, 0, -1, 0};
    
    private void sink(char[][] grid, int i, int k) {
        if (i < 0 || k < 0 || i >= grid.length || k >= grid[0].length || grid[i][k] == '0') return;
        grid[i][k] = '0';
        for (int z = 0; z < 4; z++) {
            sink(grid, i + d[z], k + d[z + 1]);
        }
    }
}

以上是关于算法:求岛屿的数量200. Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章

200 Number of Islands 岛屿的个数

LeetCode 200:Number of Islands

LeetCode 200. 岛屿数量 (BFS)

[LeetCode] 200. Number of Islands(岛屿的数目)

Leetcode200. 岛屿数量(JAVAdfs)

LeetCode | 0200. Number of Islands岛屿数量Python