LeetCode *** 200. Number of Islands (Depth-first Search)

来源:互联网 发布:flash软件下载教程 编辑:程序博客网 时间:2024/05/11 05:02

题目:

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:

11110110101100000000

Answer: 1

Example 2:

11000110000010000011

Answer: 3


分析:

利用深搜遍历,最终获得结果。


代码:

class Solution {public:    int num=0,n,m;    int numIslands(vector<vector<char>>& grid) {        if(grid.size()<1)return 0;        n=grid.size(),m=grid[0].size();        for(int i=0;i<n;++i)            for(int j=0;j<m;++j)                if(grid[i][j]=='1'){                    num++;                    dfs(grid,i,j);                }        return num;    }    void dfs(vector<vector<char>>& grid,int s,int e){        grid[s][e]='0';        if(s>0&&grid[s-1][e]=='1')dfs(grid,s-1,e);        if(s<n-1&&grid[s+1][e]=='1')dfs(grid,s+1,e);        if(e>0&&grid[s][e-1]=='1')dfs(grid,s,e-1);        if(e<m-1&&grid[s][e+1]=='1')dfs(grid,s,e+1);    }};

0 0
原创粉丝点击