我参加了一个编码竞赛,我非常接近于解决下面的问题,但我的代码由于某种原因没有运行=(
以下是问题链接: https://leetcode.com/contest/leetcode-weekly-contest-53/problems/max-area-of-island/
我的解决方案:
class Solution(object):
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
self.longest = 0
self.count = 0
row = len(grid)
col = len(grid[0])
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
self.count += 1
current = 1
self.countIsland(i, j, current, grid)
return self.longest
def countIsland(self, k, z, current, grid):
print(str(k) + "," + str(z) + "=" + str(current))
grid[k][z] = -1
if k > 0 and grid[k-1][z] == 1:
return self.countIsland(k-1, z, current+1, grid)
if k < (len(grid)-1) and grid[k+1][z] == 1:
return self.countIsland(k+1, z, current+1, grid)
if z > 0 and grid[k][z - 1] == 1:
return self.countIsland(k, z-1, current+1, grid)
if z < (len(grid[0])-1) and grid[k][z+1] == 1:
return self.countIsland(k, z+1, current+1, grid)
self.longest = max(self.longest, current)
return current
我1点下班,我得到5分而不是6分。如果您尝试在IDE中运行它,我的print语句将显示,对于递归的最后一次调用,current值正在被重新初始化,这不是我想要的。有什么想法为什么?在
谢谢!在
基本方法是直观的。我们使用DFS在每个可能的位置扩展岛屿。当一个岛上的牢房被访问时,我们会“击沉”它。下面是我的Java实现,并通过了Leetcode上的所有测试。在
相关问题 更多 >
编程相关推荐