200. Number of Islands 题解

来源:互联网 发布:部落冲突英雄升级数据 编辑:程序博客网 时间:2024/06/06 03:19

200. 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


题目链接:200. Number of Islands


算法描述:


       由题可知,给出一个矩阵,矩阵中 “1” 表示陆地,“0” 表示水域,横竖相连的 “1” 表示相同的一块陆地,最后返回陆地的数量。


        我们可以用深度优先遍历来做这道题,当访问到 “1” 时(即访问到陆地),根据要求,横竖相连的 “1” 表示的是同一块陆地,我们首先将它由 “1” 至为 “0”。之后需要继续访问它的上下左右(即进入 dfs_func 函数),dfs_func 函数在遍历的时候便将横竖相连的同一块陆地访问完毕并至为 “0”。对同一块陆地访问完毕后将返回值 ans 加一。


代码:

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int ans=0;
        if(grid.empty()||grid[0].empty()){
            return ans;
        } 
        int h=grid.size();
        int v=grid[0].size();


        for(int i=0; i<h; i++){
            for(int j=0; j<v; j++){
                if(grid[i][j]=='1'){
                    dfs_func(grid,i,j,h,v);
                    ans++;
                }
            }
        }
        return ans;
    }
    
    void dfs_func(vector<vector<char>>&grid, int i, int j, int h, int v){
        grid[i][j]='0';
        if(i>0 && grid[i-1][j]=='1'){
            dfs_func(grid,i-1,j,h,v);
        }
        if(i<h-1 && grid[i+1][j]=='1'){
            dfs_func(grid,i+1,j,h,v);
        }
        if(j>0 && grid[i][j-1]=='1'){
            dfs_func(grid,i,j-1,h,v);
        }
        if(j<v-1 && grid[i][j+1]=='1'){
            dfs_func(grid, i, j+1,h,v);
        }
    }
    
};

0 0
原创粉丝点击