Number of Islands

题目:

Given a boolean 2D matrix, find the number of islands.

example:
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]

分析:

这是一道典型的搜索,计数问题,可以用dfs和bfs两种方法来解。

解法bfs:

class Solution {
public:
    /**
     * @param grid a boolean 2D matrix
     * @return an integer
     */
    void bfs(vector<vector<bool> > &grid, int i, int j) {
        queue<int> Q;
        int m = grid.size();
        int n = grid[0].size();
        grid[i][j] = false;
        int code = i * n + j;
        Q.push(code);
        while (!Q.empty() ) {
            code = Q.front();
            Q.pop();
            int x = code / n;
            int y = code % n;
            if (x - 1 >= 0 && grid[x - 1][y] == true) {
                Q.push( (x - 1) * n + y);
                grid[x - 1][y] = false;
            }
            if (x + 1 < m && grid[x + 1][y] == true) {
                Q.push( (x + 1) * n + y);
                grid[x + 1][y] = false;
            }
            if (y - 1 >= 0 && grid[x][y - 1] == true) {
                Q.push(x * n + y - 1);
                grid[x][y - 1] = false;
            }
            if (y + 1 < n && grid[x][y + 1] == true) {
                Q.push(x * n + y + 1);
                grid[x][y + 1] = false;
            }
        }
    }

    int numIslands(vector<vector<bool>>& grid) {
        // Write your code here
        if (grid.size() == 0 || grid[0].size() == 0) {
            return 0;
        }
        int m = grid.size();
        int n = grid[0].size();
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == true) {
                    count++;
                    bfs(grid, i, j);
                }
            }
        }
        return count;
    }
};

解法dfs:

public:
    /**
     * @param grid a boolean 2D matrix
     * @return an integer
     */
    void dfs(vector<vector<bool> > &grid, int i, int j) {
        if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() ) {
            return;
        }
        if (grid[i][j] == false) {
            return;
        }
        grid[i][j] = false;
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    } 

    int numIslands(vector<vector<bool>>& grid) {
        // Write your code here
        if (grid.size() == 0 || grid[0].size() == 0) {
            return 0;
        }
        int m = grid.size();
        int n = grid[0].size();
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == true) {
                    count++;
                    dfs(grid, i, j);
                }
            }
        }
        return count;
    }
};

results matching ""

    No results matching ""