python - 为什么python for循环在while循环中导致无限循环?
问题描述
我有这个解决方案
directions = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1],
]
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
queue=deque()
fresh_oranges=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==2:
queue.append([i,j])
if grid[i][j]==1:
fresh_oranges+=1
current_queue_size=len(queue)
minutes=0
while len(queue)>0:
if current_queue_size==0:
current_queue_size=len(queue)
minutes+=1
current_orange=queue.popleft()
current_queue_size-=1
row=current_orange[0]
col=current_orange[1]
for direction in directions:
next_row=row+direction[0]
next_col=col+direction[1]
if next_row<0 or next_row>=len(grid) or next_col<0 or next_col>=len(grid[0]):
continue
if grid[next_row][next_col]==1:
grid[next_row][next_col]==2
fresh_oranges-=1
queue.append([next_row,next_col])
if fresh_oranges!=0:
return -1
return minutes
这部分代码导致循环:
if grid[next_row][next_col]==1:
grid[next_row][next_col]==2
fresh_oranges-=1
queue.append([next_row,next_col])
这是一个经典的广度优先搜索,我在队列“[next_row,next_col]”中添加一些内容,然后弹出一些“current_orange=queue.popleft()”直到队列为空。为什么这会导致无限循环?
s=Solution()
s.orangesRotting([[2,1,1],[1,1,0],[0,1,1]])
解决方案
推荐阅读
- javascript - 如何在Angular 2中传递变量以切换手风琴内的特定面板
- php - 用 PHP 发送电子邮件 - 表单
- postgresql - PostgreSQL 按所有字段分组
- python - 需要在列表列表中找到最大值
- jquery - SVG 元素与之前的兄弟 SVG 重叠
- vb.net - vb6 - 使用结构作为类属性类型
- react-native - 在重新启动应用程序不起作用时设置权限
- google-cloud-platform - 如何设置从本地到 Google Cloud VPC 的 VPN
- javascript - JS ClipboardEvent 剪贴板数据始终为空
- angular - Angular 4 - ngFor 下拉/选择选项在 IE11 上非常慢,如何优化 ngDoCheck 执行?