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 天前
牛客周赛 Round 108
数据结构·c++·算法·动态规划·图论·广度优先·推荐算法
_Coin_-3 天前
算法训练营DAY58 第十一章:图论part08
数据结构·算法·图论
闪电麦坤956 天前
数据结构:图的表示 (Representation of Graphs)
数据结构·算法·图论
BlackPercy6 天前
【图论】Graphs.jl 最小生成树算法文档
算法·图论
SuperCandyXu7 天前
洛谷 P3128 [USACO15DEC] Max Flow P -普及+/提高
c++·算法·图论·洛谷
zc.ovo7 天前
牛子图论1(二分图+连通性)
数据结构·c++·算法·深度优先·图论
ltrbless7 天前
最小生成树算法详解
算法·排序算法·图论
love you joyfully8 天前
图论简介与图神经网络(Dijkstra算法,图卷积网络GCN实战)
人工智能·深度学习·神经网络·算法·贪心算法·图论
YA10JUN9 天前
数据结构基础--最小生成树
数据结构·算法·图论
啊我不会诶12 天前
【图论】最短路算法
算法·图论