LeetCode200: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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

LeetCode:链接

给定一个由字符‘1’(陆地)和‘0’(水域)组成的二维网格地图,计算岛屿的个数。岛屿被水域环绕,由竖直或者水平方向邻接的陆地构成。你可以假设网格地图的四条边都被水域包围。

做法是,我们对每个有“1"的位置进行dfs,把和它四联通的位置全部变成“0”,这样就能把一个点推广到一个岛。

所以,我们总的进行了dfs的次数,就是总过有多少个岛的数目。注意理解dfs函数的意义:已知当前是1,把它周围相邻的所有1全部转成0。

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        m = len(grid)
        if m == 0:
            return 0
        n = len(grid[0])
        ans = 0
        for x in range(m):
            for y in range(n):
                if grid[x][y] == '1':
                    ans += 1
                    self.dfs(grid, x, y, m, n)
        return ans

    def dfs(self, grid, x, y, m ,n):
        if x < 0 or y < 0 or x >= m or y >= n or grid[x][y] == '0':
            return 
        grid[x][y] = '0'
        self.dfs(grid, x-1, y, m, n)
        self.dfs(grid, x+1, y, m, n)
        self.dfs(grid, x, y+1, m, n)
        self.dfs(grid, x, y-1, m, n)

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/86291596