200 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:

    11110
    11010
    11000
    00000
    

    Answer: 1

  • Example 2:

    11000
    11000
    00100
    00011
    

    Answer: 3

Solution

class Solution {
public:
    void explore(vector<vector<char>>& grid, int i, int j ) {
        int m = grid.size();
        int n = grid[0].size();
        stack<pair<int, int>> s;
        s.push(pair<int, int>(i, j));
        while ( ! s.empty() ) {
            int n1 = s.top().first, n2 = s.top().second;
            s.pop();
            grid[n1][n2] = '0';
            if ( n1-1 >= 0 and grid[n1-1][n2] == '1' ) s.push(pair<int, int>(n1-1, n2));
            if ( n1+1 <= m-1 and grid[n1+1][n2] == '1' ) s.push(pair<int, int>(n1+1, n2));
            if ( n2-1 >= 0 and grid[n1][n2-1] == '1' ) s.push(pair<int, int>(n1, n2-1));
            if ( n2+1 <= n-1 and grid[n1][n2+1] == '1' ) s.push(pair<int, int>(n1, n2+1));
        }
        return;
    }
    int numIslands(vector<vector<char>>& grid) {
        int m = grid.size();
        if ( m == 0 ) return 0;
        int n = grid[0].size();
        if ( n == 0 ) return 0;
        int icount = 0;
        for ( int i = 0; i <= m-1; i++ ) {
            for ( int j = 0; j <= n-1; j++ ) {
                if ( grid[i][j] == '0' ) continue;
                icount += 1;
                explore(grid, i, j);
            }
        }
        return icount;
    }
};

results matching ""

    No results matching ""