文章目录
- 最大岛屿体积
最大岛屿体积
- 大于0的数表示陆地,0表示水,请计算由陆地、水组成的网格中最大岛屿的体积;
- 陆地的数字之和表示所在岛屿的体积,岛屿总是被水包围,并且每座岛屿只能由水平或者垂直方向上相邻的陆地连接形成;
- 假设该网格的四条边均被水包围;
输入描述:
第一行输入网格的宽度、高度;
后面几行输入网格数据;
输出描述:
输出岛屿的最大体积
示例
输入:
5 5
0 1 1 0 0
0 1 1 0 0
0 0 0 0 0
0 0 1 2 3
0 0 1 3 9
输出:
19
python实现:
- BFS,借助队列;
- 遍历二维数组中的每个值,当其大于0且未被访问时,开始广度优先搜索,并计算当前岛屿的体积,与默认的最大值比较,取两者中的最大值;
- 注意避免位置的重复入队,会导致某些陆地值的重复计算;
col, row = list(map(int, input().strip().split()))
matrix = []
for i in range(row):matrix.append(list(map(int, input().strip().split())))# 记录岛屿的最大体积
max_vol = 0
# 标记是否已访问
visited = [[0 for j in range(col)] for i in range(row)]# 遍历二维数组中的每个元素,大于0时则开始广度优先搜索陆地
for i in range(row):for j in range(col):if matrix[i][j] > 0 and visited[i][j] == 0: # 陆地的起始点,并开始广度优先搜索# BFS 借助队列q = [(i, j)] # 存入起始点# 四个方向directions = [0, 1, 0, -1, 0]temp_vol = 0 # 统计当前岛屿的体积while q:cur_x, cur_y = q.pop(0)print("cur x, y", cur_x, cur_y)temp_vol += matrix[cur_x][cur_y]visited[cur_x][cur_y] = 1# 取四个方向的位置for d in range(4):next_x = cur_x + directions[d]next_y = cur_y + directions[d+1]if next_x >= 0 and next_x < row and next_y >= 0 and next_y < col and visited[next_x][next_y] == 0 and matrix[next_x][next_y] > 0:if (next_x, next_y) not in q: # 注意去重q.append((next_x, next_y))# 取岛屿体积的最大值print(temp_vol)max_vol = max(max_vol, temp_vol)print(max_vol)