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

岛屿问题的第一题,已经给出矩阵中的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)
           
原文地址:https://www.cnblogs.com/sherylwang/p/5580124.html