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;
    }
};

你可能感兴趣的:(LeetCode,DFS,bfs)