200. Number of Islands

来源:互联网 发布:topcashback软件 编辑:程序博客网 时间:2024/06/05 06:01

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


利用dfs,每次遇到一个‘1’,都遍历其周围。将周围‘1’都置为‘2’

代码:

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


0 0
原创粉丝点击