使用DFS的岛屿数量
帮助我发现错误
答案错误 细节 输入 实际“ 0”,“ 1”,“ 0”,“ 0”],[“ 0”,“ 0”,“ 0”,“ 1”,“ 1”]]] 输出 1 预期的 3
使用深度第一遍历来计数岛屿
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
#Nested loop to go over our Grid
#use depth first traversal in second loop to explore neighbors
visited = set()
count = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if (self.explore(grid,row,col,visited)):
count +=1
return count
def explore(self,grid,row,col,visited):
#catch if we are out of bounds
rowInbound = 0 <= row and row < len(grid)
colInbound = 0 <= col and col < len(grid[0])
if not rowInbound or not colInbound:
return False
#check if current is water
position = grid[row][col]
if (position == '0'):
return False
#check for visited
if position in visited:
return False
visited.add(position)
self.explore(grid,row-1,col,visited)
self.explore(grid,row+1,col,visited)
self.explore(grid,row,col-1,visited)
self.explore(grid,row,col+1,visited)
#this true will symbolize that I am now exploring a new island
return True
Help me spot the error
Wrong Answer
Details
Input
[["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output
1
Expected
3
Using a depth first traversal to count islands
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
#Nested loop to go over our Grid
#use depth first traversal in second loop to explore neighbors
visited = set()
count = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if (self.explore(grid,row,col,visited)):
count +=1
return count
def explore(self,grid,row,col,visited):
#catch if we are out of bounds
rowInbound = 0 <= row and row < len(grid)
colInbound = 0 <= col and col < len(grid[0])
if not rowInbound or not colInbound:
return False
#check if current is water
position = grid[row][col]
if (position == '0'):
return False
#check for visited
if position in visited:
return False
visited.add(position)
self.explore(grid,row-1,col,visited)
self.explore(grid,row+1,col,visited)
self.explore(grid,row,col-1,visited)
self.explore(grid,row,col+1,visited)
#this true will symbolize that I am now exploring a new island
return True
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是
位置
与访问
无关。位置
是单元格的 content ,而访问
应收集单元格的坐标。因此,将相关部分更改为:
The problem is that
position
has nothing to do withvisited
.position
is the content of a cell, whilevisited
should collect coordinates of a cell.So change the relevant part to: