Number of Islands

LeetCode #200 Interview


Description:

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:

Example 1:

11110
11010
11000
00000
Answer: 1

Example 2:

11000
11000
00100
00011
Answer: 3

Idea:

非常typical的DFS

注意这样expand children比较简洁:

vector<pair<int, int>> move={{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

for(auto e: move){
    int k=i+e.first;
    int l=j+e.second;

    if(k>=0 && k<m && l>=0 && l<n && grid[k][l]=='1'&& !visited[k][l])
        DFS(grid, k, l, visited);            
}

Code:

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty()) return 0;

        int m=grid.size();
        int n=grid[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        int count=0;

        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(grid[i][j]=='1' && !visited[i][j]){
                    count++;
                    DFS(grid, i, j, visited);
                }
            }
        }
        return count;
    }

    void DFS(const vector<vector<char>>& grid, int i, int j, vector<vector<bool>>& visited){
        visited[i][j] = true; // Mark as visited.
        int m=grid.size();
        int n=grid[0].size();

        // move.first is X move, move.second is Y move
        vector<pair<int, int>> move={{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

        for(auto e: move){
            int k=i+e.first;
            int l=j+e.second;

            if(k>=0 && k<m && l>=0 && l<n && grid[k][l]=='1'&& !visited[k][l])
                DFS(grid, k, l, visited);            
        }

    }
};

results matching ""

    No results matching ""