Number of Islands - leetcode


原題リンク
タイトル:
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

考え方:
         ,             .     dfs/bfs   . 
(          ,   dfs/bfs        )

code
class Solution {
public:
    bool check(int m, int n, int x, int y) {
        return x >= 0 && x < m && y >= 0 && y < n;
    }

    void dfs(vector<vector<char>>& grid, int m, int n, int x, int y) {
        if(!check(m, n, x, y)) return;
        if(grid[x][y] != '1') return;
        // set statue: visited
        grid[x][y] = 'v';
        dfs(grid, m, n, x - 1, y);
        dfs(grid, m, n, x + 1, y);
        dfs(grid, m, n, x, y - 1);
        dfs(grid, m, n, x, y + 1);
    }

    int numIslands(vector<vector<char>>& grid) {
        if(grid.size() == 0) return 0;

        int m = grid.size();
        int n = grid[0].size();

        int cnt = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                // if grid[i][j] has been not visited and is equal to '1', 
                // then dfs
                if(grid[i][j] == '1') {
                    dfs(grid, m, n, i, j);
                    cnt++;
                }
            }
        }

        return cnt;
    }
};