207、【图论】孤岛的总面积

题目


思路

相比于 206、【图论】岛屿数量,就是在这个代码的基础上。先遍历边界,将边界连接的岛屿变为0,然后再计算一遍当前为1的岛屿面积。

代码实现

python 复制代码
import collections

n, m = list(map(int, input().split()))
graph = []

for _ in range(n):
    graph.append(list(map(int, input().split())))

directions = [[0, 1], [0, -1], [-1, 0], [1, 0]]
res = 0

def traversal(i, j):
    que = collections.deque()
    que.append([i, j])
    graph[i][j] = 0

    global res  
    res += 1

    while que:
        x, y = que.popleft()
        for move_x, move_y in directions:
            next_x, next_y = x + move_x, y + move_y
            if next_x < 0 or next_x >= n or next_y < 0 or next_y >= m:
                continue
            elif graph[next_x][next_y] == 1:
                res += 1            
                graph[next_x][next_y] = 0                            
                que.append([next_x, next_y])


for i in range(n):
    if graph[i][0] == 1:
        traversal(i, 0)
    if graph[i][m - 1] == 1:
        traversal(i, m - 1)

for i in range(m):
    if graph[0][i] == 1:
        traversal(0, i)
    if graph[n - 1][i] == 1:
        traversal(n - 1, i)

res = 0
for i in range(n):
    for j in range(m):
        if graph[i][j] == 1:
            traversal(i, j)            


print(res)

参考文章:101. 孤岛的总面积

相关推荐
汀、人工智能3 小时前
[特殊字符] 第67课:跳跃游戏II
数据结构·算法·数据库架构·图论·bfs·跳跃游戏ii
苏纪云4 小时前
洛谷题目练习——二分+搜索+贪心+数学
算法·图论
君义_noip6 小时前
信息学奥赛一本通 4149:【GESP2509七级】连通图 | 洛谷 P14077 [GESP202509 七级] 连通图
c++·图论·gesp·信息学奥赛
汀、人工智能1 天前
[特殊字符] 第74课:完全平方数
数据结构·算法·数据库架构·图论·bfs·完全平方数
ambition202421 天前
斐波那契取模问题的深入分析:为什么提前取模是关键的
c语言·数据结构·c++·算法·图论
汀、人工智能1 天前
[特殊字符] 第73课:打家劫舍
数据结构·算法·数据库架构·图论·bfs·打家劫舍
汀、人工智能1 天前
[特殊字符] 第41课:翻转二叉树
数据结构·算法·数据库架构·图论·bfs·翻转二叉树
汀、人工智能1 天前
[特殊字符] 第46课:验证二叉搜索树
数据结构·算法·数据库架构·图论·bfs·验证二叉搜索树
汀、人工智能1 天前
[特殊字符] 第50课:最大路径和
数据结构·算法·数据库架构·图论·bfs·最大路径和
汀、人工智能2 天前
[特殊字符] 第40课:二叉树最大深度
数据结构·算法·数据库架构·图论·bfs·二叉树最大深度