首页 > 其他 > 详细

Number of Islands

时间:2016-06-13 13:07:45      阅读:117      评论: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

岛屿问题的第一题,已经给出矩阵中的01分布,求在这种情况下的岛屿总个数。解题思路是DFS,即每次找一个为1的点,在其上下左右进行4个DFS,但是需要注意的是已经遍历过的岛屿,一定是已经加入成为大陆或者单独成为岛屿,已经加入了count的个数,为了避免重复遍历,需要已遍历过的点置为0. 代码时间复杂度为O(4*m*n),空间复杂为栈空间,O(min(m,n)).代码如下:

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if not grid or not grid[0]:
            return 0
        count = 0
        dx = [0, 0, -1, 1]
        dy = [1, -1, 0, 0]
        for i in xrange(len(grid)):
            for j in xrange(len(grid[0])): 
                if grid[i][j] == 1:
                    self.removeIslands(i, j, grid, dx, dy)
                    count += 1
        return count
        
    def removeIslands(self, x, y, grid, dx, dy):
        grid[x][y] = 0
        for i in xrange(4):
            nextX = x + dx[i]
            nextY = y +dy[i]
            if 0 <= nextX < len(grid) and 0 <= nextY < len(grid[0]) and grid[nextX][nextY] == 1:
                self.removeIslands(nextX, nextY, grid, dx, dy)
           

 

Number of Islands

原文:http://www.cnblogs.com/sherylwang/p/5580124.html

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