跳转至

200.Number of Islands

Tags: Medium DFS BFS Union Find

Links: https://leetcode.com/problems/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

class Solution {
    vector<vector<int>> direction = {{1,0}, {-1,0}, {0,1}, {0,-1}};
public:
    inline bool canMove(vector<vector<char>>& grid, int i, int j) {
        int m = grid.size();
        int n = grid[0].size();
        return (0 <= i && i < m && 0 <= j && j < n && grid[i][j] == '1');
    }

    void DFS(vector<vector<char>>& grid, int row, int col) {
        grid[row][col] = '0';
        for (int i = 0; i < 4; ++i) {
            int nextRow = row + direction[i][0];
            int nextCol = col + direction[i][1];
            if (canMove(grid, nextRow, nextCol)) {
                DFS(grid, nextRow, nextCol);
            }
        }
    }

    int numIslands(vector<vector<char>>& grid) {
        int cnt = 0;
        for (int i = 0; i < grid.size(); ++i) {
            for (int j = 0; j < grid[i].size(); ++j) {
                if (grid[i][j] == '1') {
                    DFS(grid, i, j);
                    ++cnt;
                }
            }
        }

        return cnt;
    }
};

很典型的Lake Counting问题,和《挑战程序设计》里的例题解法基本一模一样。