200_岛屿数量


"""
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:
输入:
11110
11010
11000
00000

输出: 1

示例 2:
输入:
11000
11000
00100
00011

输出: 3
"""


directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]

def numIslands1(grid):
    m = len(grid)
    n = len(grid[0])
    if m == 0:
        return 0

    marked = [[False for _ in range(n)] for _ in range(m)]
    count = 0
    for i in range(m):
        for j in range(n):
            if not marked[i][j] and grid[i][j] == '1':
                count += 1
                dfs(grid, i, j, m, n, marked)
    return count

def dfs(grid, i, j, m, n, marked):
    marked[i][j] = True
    for direction in directions:
        new_i = i + direction[0]
        new_j = j + direction[1]
        if 0 <= new_i < m and 0 <= new_j < n and not marked[new_i][new_j] and grid[new_i][new_j] == '1':
            dfs(grid, new_i, new_j, m, n, marked)


# 方法二
def flag_islands(i, j, grid, flag):
    # 上
    if i - 1 >=0 and grid[i-1][j] == '1':
        grid[i-1][j] = flag
        flag_islands(i-1, j, grid, flag)
    
    # 下
    if i+1 < len(grid) and grid[i+1][j] == '1':
        grid[i+1][j] = flag
        flag_islands(i+1, j, grid, flag)
    
    # 左
    if j - 1 >= 0 and grid[i][j-1] == '1':
        grid[i][j-1] = flag
        flag_islands(i, j-1, grid, flag)
    
    # 右
    if j + 1 < len(grid[i]) and grid[i][j+1] == '1':
        grid[i][j+1] = flag
        flag_islands(i, j+1, grid, flag)

def numIslands2(grid):
    if not grid:
        return 0
    result = 0
    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if grid[i][j] != '1':
                continue
            flag_islands(i, j, grid, result)
            result += 1
    return result



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值