首页 > 解决方案 > 为什么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]])

标签: pythonfor-loopwhile-loop

解决方案


推荐阅读