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 天前
是否存在路径(FIFOBB算法)
算法·蓝桥杯·图论
闻缺陷则喜何志丹5 天前
【二分图 图论】P9384 [THUPC 2023 决赛] 着色|普及+
c++·算法·图论·二分图·洛谷
鸽子炖汤5 天前
LRC and VIP
c++·算法·图论
JK0x077 天前
代码随想录算法训练营 Day61 图论ⅩⅠ Floyd A※ 最短路径算法
算法·图论
qq_447429417 天前
数据结构与算法:图论——拓扑排序
linux·c语言·学习·图论
zc.ovo7 天前
图论刷题1
算法·深度优先·图论
珂朵莉MM7 天前
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论
蒙奇D索大7 天前
【数据结构】图论核心算法解析:深度优先搜索(DFS)的纵深遍历与生成树实战指南
数据结构·算法·深度优先·图论·图搜索算法
ShiinaMashirol7 天前
代码随想录打卡|Day50 图论(拓扑排序精讲 、dijkstra(朴素版)精讲 )
java·图论
JK0x0710 天前
代码随想录算法训练营 Day60 图论Ⅹ Bellmen_ford 系列算法
android·算法·图论