Python 实现【最大岛屿体积】

B站影视 韩国电影 2025-04-03 17:16 1

摘要:def max_island_volume(grid):if not grid:return 0max_volume = 0rows, cols = len(grid), len(grid[0])visited = [[False for _ in range

def max_island_volume(grid):if not grid:return 0max_volume = 0rows, cols = len(grid), len(grid[0])visited = [[False for _ in range(cols)] for _ in range(rows)]for i in range(rows):for j in range(cols):if grid[i][j] > 0 and not visited[i][j]:current_volume = 0stack = [(i, j)]visited[i][j] = Truewhile stack:x, y = stack.popcurrent_volume += grid[x][y]for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:nx, ny = x + dx, y + dyif 0 0 and not visited[nx][ny]:visited[nx][ny] = Truestack.append((nx, ny))max_volume = max(max_volume, current_volume)return max_volume# 读取输入width, height = map(int, input.split)grid = for _ in range(height):row = list(map(int, input.split))grid.append(row)# 计算并输出结果print(max_island_volume(grid))

来源:科学新鲜事

相关推荐