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

相关推荐
失散131 天前
软件设计师——03 数据结构(下)
数据结构·软考·图论·软件设计师
YA10JUN2 天前
C++版搜索与图论算法
c++·算法·图论
蒙奇D索大3 天前
【数据结构】图论核心应用:关键路径算法详解——从AOE网到项目管理实战
数据结构·笔记·学习·考研·算法·图论·改行学it
钮钴禄·爱因斯晨4 天前
数据结构|图论:从数据结构到工程实践的核心引擎
c语言·数据结构·图论
heeheeai5 天前
kotlin图算法
算法·kotlin·图论
杨小码不BUG7 天前
CSP-J/S初赛知识点精讲-图论
c++·算法·图论··编码·csp-j/s初赛
(❁´◡`❁)Jimmy(❁´◡`❁)8 天前
【Trie】 UVA1401 Remember the Word
算法·word·图论
qq_418247889 天前
论文阅读:TEMPORAL GRAPH NETWORKS FOR DEEP LEARNING ON DYNAMIC GRAPHS
论文阅读·人工智能·深度学习·图论
希望201719 天前
图论基础知识
算法·图论
行走的bug...19 天前
用图论来解决问题
算法·图论