Saturday, July 22, 2017

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:
    bool dfs(vector<vector<char>>& grid, int i, int j,
             vector<vector<bool>>& visited, int& ans) {
        if (i < 0 || i >= grid.size() ||
            j < 0 || j >= grid[0].size() ||
            visited[i][j] || grid[i][j] == '0') {
           return false;
        }
        visited[i][j] = true;
        dfs(grid, i, j + 1, visited, ans);
        dfs(grid, i, j - 1, visited, ans);
        dfs(grid, i + 1, j, visited, ans);
        dfs(grid, i - 1, j, visited, ans);
        return true;
       
    }
    int numIslands(vector<vector<char>>& grid) {
        int ans = 1;
        int row = grid.size();
        if (row == 0) {
            return 0;
        }
        int col = grid[0].size();
        vector<vector<bool> > visited(grid.size(), vector<bool>(grid[0].size(), false));
       
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (dfs(grid, i, j, visited, ans)) {
                    ans++;
                }
            }
        }
        return ans - 1;
    }
};

======== No need of visited information =====

void dfs(vector<vector<char>> &grid, int x, int y) {
 4         if (x < 0 || x >= grid.size()) return;
 5         if (y < 0 || y >= grid[0].size()) return;
 6         if (grid[x][y] != '1') return;
 7         grid[x][y] = 'X';
 8         dfs(grid, x + 1, y);
 9         dfs(grid, x - 1, y);
10         dfs(grid, x, y + 1);
11         dfs(grid, x, y - 1);
12     }
13     
14     int numIslands(vector<vector<char>> &grid) {
15         if (grid.empty() || grid[0].empty()) return 0;
16         int N = grid.size(), M = grid[0].size();
17         int cnt = 0;
18         for (int i = 0; i < N; ++i) {
19             for (int j = 0; j < M; ++j) {
20                 if (grid[i][j] == '1') {
21                     dfs(grid, i, j);
22                     ++cnt;
23                 }
24             }
25         }
26         return cnt;
27     }

No comments:

Post a Comment