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. 孤岛的总面积

相关推荐
AICodeThunder5 小时前
【S组篇】C++知识点总结(1):并查集基础
c语言·数据结构·c++·算法·图论
极客数模2 天前
2025年MathorCup 大数据竞赛明日开赛,注意事项!论文提交规范、模板、承诺书正确使用!2025年第六届MathorCup数学应用挑战赛——大数据竞赛
大数据·python·算法·matlab·图论·比赛推荐
大数据张老师2 天前
【无标题】
算法·图论
许小禾上学记2 天前
学习笔记 | 图论基础
笔记·学习·图论
小李小李快乐不已2 天前
图论理论基础(1)
数据结构·算法·leetcode·深度优先·图论·广度优先·宽度优先
大数据张老师3 天前
数据结构——广度优先搜索
数据结构·图论·宽度优先
YSRM4 天前
Leetcode+Java+图论+最小生成树&拓扑排序
java·leetcode·图论
YSRM4 天前
Leetcode+Java+图论+并查集
算法·leetcode·图论
YSRM4 天前
Leetcode+Java+图论II
java·leetcode·图论
晚枫~5 天前
图论基础:探索节点与关系的复杂网络
网络·数据结构·图论