岛屿数量

问题:

# 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。 
#
# 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
#
# 此外,你可以假设该网格的四条边均被水包围。
#
#
#
# 示例 1:
#
#
# 输入:grid = [
# ["1","1","1","1","0"],
# ["1","1","0","1","0"],
# ["1","1","0","0","0"],
# ["0","0","0","0","0"]
# ]
# 输出:1

方法:dfs,bfs,并查集

# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid or not grid[0]:
            return 0
        m, n = len(grid), len(grid[0])
        count = 0

        def dfs(i, j):
            # 数据抹零
            grid[i][j] = '0'
            # 查找上下左右
            for dx, dy in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
                x, y = i + dx, j + dy
                if 0 <= x < m and 0 <= y < n and grid[x][y] == '1':
                    dfs(x, y)
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                    count += 1
                    dfs(i, j)
        return count
# leetcode submit region end(Prohibit modification and deletion)

 性价比之王-bfs

m, n = len(grid), len(grid[0])
_grid = [[int(grid[i][j]) for j in range(n)] for i in range(m)]
def islands_count(grid):
    nums = 0
    visited = set({})
    m, n = len(grid), len(grid[0])
    for i in range(m):
        for j in range(n):
            # 节点为1且没有被访问过,广度搜索
            if grid[i][j] and (i,j) not in visited:
                island_bfs(grid, i, j, visited)
                nums += 1
    return nums

def island_bfs(grid, i, j, visited):
    queue = collections.deque([(i,j)])  # 节点加入队列同时维护访问集合,队列里都是要遍历的元素
    visited.add((i,j))
    while queue:
        x, y = queue.popleft()
        for delta_x, delta_y in directions:  # 加入偏移量获得新节点的坐标
            next_x = x + delta_x
            next_y = y + delta_y
            if not is_valid(grid, next_x, next_y, visited):  # 验证新节点是否合法,不合法则没有必要加入队列遍历
                continue
            queue.append((next_x, next_y))  # 同步队列和访问集合
            visited.add((next_x, next_y))

def is_valid(grid, x, y, visited):
    m, n = len(grid), len(grid[0])
    if not (0<=x<m and 0<=y<n):
        return False
    if (x,y) in visited:
        return False
    return grid[x][y]

 

posted @ 2021-05-26 23:35  今夜无风  阅读(42)  评论(0编辑  收藏  举报