美文网首页Leetcode
Leetcode.200.Number of Islands

Leetcode.200.Number of Islands

作者: Jimmy木 | 来源:发表于2019-11-20 10:23 被阅读0次

    题目

    给定一个二维数组, 由'1'和'0'组成, 如果'1'周围都是'0', 计算加1, 最外围默认都是0. 求连通后的'1'的个数.

    Input: [['1','1','1'],['0','1','0'],['1','1','1']]
    Output: 1
    Input: [['1','1','0','0','0'],['1','1','0','0','0'],['0','0','1','0','0'],['0','0','0','1','1']]
    Output: 3
    Input: [['1','1','1','1','0'],['1','1','0','1','0'],['1','1','0','0','0'],['0','0','0','0','0']]
    Output: 1
    

    思路

    DFS. 采用递归, 每次对'1'的上下左右进行递归. 遇到'1',则置为0, 遇到'0', 则停止.

    void numIslandsRecrution(vector<vector<char>>& grid,int i, int j) {
        if (i < 0 || i >= grid.size() ||
            j < 0 || j >= grid[i].size() ||
            grid[i][j] == '0') {
            return ;
        }
    
        grid[i][j] = '0';
        numIslandsRecrution(grid,i+1,j);
        numIslandsRecrution(grid,i-1,j);
        numIslandsRecrution(grid,i,j+1);
        numIslandsRecrution(grid,i,j-1);
    }
    
    int numIslands(vector<vector<char>>& grid) {
        int res = 0;
        for (int i = 0;i < grid.size();i++) {
            for(int j = 0; j < grid[i].size();j++) {
                if (grid[i][j] == '1') {
                    res++;
                    numIslandsRecrution(grid, i, j);
                }
            }
        }
        return res;
    }
    

    总结

    熟悉DFS和BFS的工作原理, 以及常用应用场景.

    相关文章

      网友评论

        本文标题:Leetcode.200.Number of Islands

        本文链接:https://www.haomeiwen.com/subject/gnnnictx.html