題目
思路
相比于 206、【圖論】島嶼數量,就是在這個代碼的基礎上。先遍歷邊界,將邊界連接的島嶼變為0,然后再計算一遍當前為1的島嶼面積。
代碼實現
import collectionsn, 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 = 0def traversal(i, j):que = collections.deque()que.append([i, j])graph[i][j] = 0global res res += 1while que:x, y = que.popleft()for move_x, move_y in directions:next_x, next_y = x + move_x, y + move_yif next_x < 0 or next_x >= n or next_y < 0 or next_y >= m:continueelif 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. 孤島的總面積