Leetcode: 200. 岛屿数量

题目

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。


示例 1:

输入:
[
['1','1','1','1','0'],
['1','1','0','1','0'],
['1','1','0','0','0'],
['0','0','0','0','0']
]
输出: 1


示例 2:

输入:
[
['1','1','0','0','0'],
['1','1','0','0','0'],
['0','0','1','0','0'],
['0','0','0','1','1']
]
输出: 3
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。

分析

标准的搜索问题,可以使用深度优先搜索和广度优先搜索来解决,见模板。

代码

DFS:

class Solution {
    private static final int[][] next = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) return 0;
        if (grid[0] == null || grid[0].length == 0) return 0;

        int ans = 0;
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[0].length; col++) {
                if (grid[row][col] == '1') {
                    ans++;
                    dfs(grid, row, col);
                }
            }
        }
        return ans;
    }
    private void dfs(char[][] grid, int row, int col) {
        grid[row][col] = '0';
        for (int[] nex : next) {
            int nextRow = row + nex[0], nextCol = col + nex[1];
            if (nextRow >= 0 && nextRow < grid.length && nextCol >= 0 && nextCol < grid[0].length && grid[nextRow][nextCol] == '1') {
                dfs(grid, nextRow, nextCol);
            }
        }
    }
}

注意: 可以将已经遍历过的点标记为 '0', 这样可以节省 marked 数组的空间。

BFS:

class Solution {
    private int[][] next = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    private int rows;
    private int cols;
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) return 0;
        if (grid[0] == null || grid[0].length == 0) return 0;
        this.rows = grid.length;
        this.cols = grid[0].length;
        int cnt = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (grid[i][j] == '1') {
                    BFS(grid, i, j);
                    cnt++;
                }
            }
        }
        return cnt;
    }
    private void BFS(char[][] grid, int row, int col) {
        Queue> queue = new LinkedList<>();
        queue.offer(new Pair(row, col));
        grid[row][col] = '0';
        
        while (!queue.isEmpty()) {
            Pair now = queue.poll();
            for (int[] nex : next) {
                int rowNext = now.getKey() + nex[0];
                int colNext = now.getValue() + nex[1];
                if (rowNext < 0 || rowNext >= rows || colNext < 0 || colNext >= cols || grid[rowNext][colNext] != '1') continue;
                queue.offer(new Pair(rowNext, colNext));
                grid[rowNext][colNext] = '0';
            }
        }
    }
}

 

你可能感兴趣的:(leetcode)