码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 200. Number of Islands(DFS)

时间:2016-04-25 06:32:20      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

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

简单的DFS求联通块。

class Solution {
public:
    void dfs(int x,int y,vector<vector<char> >& g){
        used[x][y]=1;
        for(int i=0;i<4;i++){
            int tx=x+dx[i];
            int ty=y+dy[i];
            if(tx>=0&&tx<n&&ty>=0&&ty<m&&used[tx][ty]==0&&g[tx][ty]==1){
                dfs(tx,ty,g);
            }
        }
        return;
    }
    int numIslands(vector<vector<char> >& grid) {
        n = grid.size();
        if(n==0) return 0;
        m = grid[0].size();
        used = vector<vector<int> >(n,vector<int>(m,0));
        int ans=0;
        
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(used[i][j]==0&&grid[i][j]==1){
                    dfs(i,j,grid);
                    ans++;
                }
            }
        }
        return ans;
    }
    
private:
    int n,m;
    int dx[4]={0,0,1,-1};
    int dy[4]={1,-1,0,0};
    vector<vector<int> >used;
};

 

leetcode 200. Number of Islands(DFS)

标签:

原文地址:http://www.cnblogs.com/zywscq/p/5429124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!