首页 > 其他 > 详细

[leetcode] Number of Islands

时间:2015-04-13 00:01:58      阅读:724      评论:0      收藏:0      [点我收藏+]

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

思路:

leetcode的新题,题目思路很简单,DFS或者BFS,而且还不用回溯,直接判断,难度不大。因为自己用弱项BFS写出来了,贴出来备忘。

题解:

技术分享
class Solution {
public:
    int dir[4][2] = {{-1,0}, {0,-1}, {1,0},{0,1}};
    void dfs(vector<vector<char> > &grid, int x, int y) {
        grid[x][y] = 0;
        for(int k=0;k<4;k++) {
            int nx = x+dir[k][0];
            int ny = y+dir[k][1];
            if(nx>=0 && nx<grid.size() && ny>=0 && ny<grid[0].size())
                if(grid[nx][ny]==1)
                    dfs(grid, nx, ny);
        }
    }
    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) {
                    dfs(grid, i, j);
                    res++;
                }
        return res;
    }
};
DFS
技术分享
class Solution {
public:
    struct point {
        point(int xx=0, int yy=0): x(xx), y(yy) {}
        int x;
        int y;
    };
    int dir[4][2] = {{0,-1}, {-1,0}, {0,1}, {1,0}};
    void BFS(vector<vector<char> > &grid, int x, int y) {
        queue<point> q;
        int curx, cury;
        q.push(point(x,y));
        while(!q.empty()) {
            curx = q.front().x;
            cury = q.front().y;
            q.pop();
            grid[curx][cury] = 0;
            for(int k=0;k<4;k++) {
                int nx = curx+dir[k][0];
                int ny = cury+dir[k][1];
                if(nx>=0 && nx<grid.size() && ny>=0 && ny<grid[0].size())
                    if(grid[nx][ny]==1) {
                        q.push(point(nx,ny));
                        grid[nx][ny] = 0;
                    }
            }
        }
    }
    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;
                    BFS(grid, i,j);
                }
            }
        return res;
    }
};
BFS

 

[leetcode] Number of Islands

原文:http://www.cnblogs.com/jiasaidongqi/p/4420914.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!