200. 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

题目大意:给定一个2维数组,0代表水,1代表陆地,求岛屿的数量,相邻的陆地算一个岛屿。
比如:
示意图 - 岛屿数为 3

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        count = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == "1":
                    self.doBfs(grid, i, j)
                    count += 1
        return count



    def doBfs(self, grid, i, j):
        dep = []
        dep.append([i, j])
        while dep:
            x, y = dep.pop()
            grid[x][y] = "v"
            if x + 1 < len(grid) and grid[x + 1][y] == "1":
                dep.append([x+1, y])
            if y + 1 < len(grid[0]) and grid[x][y + 1] == "1":
                dep.append([x, y + 1])
            if x - 1 >= 0 and grid[x - 1][y] == "1":
                dep.append([x - 1, y])
            if y - 1 >= 0 and grid[x][y - 1] == "1":
                dep.append([x, y - 1])

请多多指教。

文章标题:200. Number of Islands

本文作者:顺强

发布时间:2019-04-21, 23:59:00

原始链接:http://shunqiang.ml/leetcode-200-number-of-islands/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏