Wednesday, April 8, 2015

200. Number of Islands -M

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:
Input:
11110
11010
11000
00000

Output: 1
Example 2:
Input:
11000
11000
00100
00011

Output: 3

A:


 简单的dfs罢了。

根据fb面试的失败教训,建议每次发现一个‘1’, 先设‘0‘, 再dfs。

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


No comments:

Post a Comment