LeetCode-200-岛屿数量

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

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

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

示例 1:

输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands

解题思路

将二维矩阵看作图,采用广度优先遍历
扫描矩阵,遇到陆地则将其加入队列,
当队列非空是,弹出队首,然后以它为基础将四个方向中为陆地的加入队列
元素加入队列时要将该元素设为"水",防止重复遍历
广度优先遍历的次数就是岛屿数量

代码

class Solution {
    int rows, cols;

    public int numIslands(char[][] grid) {
        rows = grid.length;
        cols = grid[0].length;
        int count = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    grid[i][j] = '0';
                    Deque deque = new LinkedList<>();
                    deque.addLast(i * cols + j); // 二维坐标转为一维索引
                    while (!deque.isEmpty()) {
                        int index = deque.removeFirst();
                        int row = index / cols, col = index % cols;
                        helper(grid, row + 1, col, deque);
                        helper(grid, row - 1, col, deque);
                        helper(grid, row, col + 1, deque);
                        helper(grid, row, col - 1, deque);
                    }
                }
            }
        }
        return count;
    }

    private void helper(char[][] grid, int i, int j, Deque deque) {
        if (i >= 0 && i < rows && j >= 0 && j < cols && grid[i][j] == '1') {
            grid[i][j] = '0';
            deque.addLast(i * cols + j);
        }
    }
}

你可能感兴趣的:(LeetCode-200-岛屿数量)