从队列 adding/removing 时获取 ConcurrentModificationException

Getting ConcurrentModificationException when adding/removing from queue

我在下面的部分算法中需要使用队列,但在 Java 中,我无法在遍历队列时修改队列。我得到一个 ConcurrentModificationException.

我该怎么办?我已经考虑了好几个小时了。

m, n = len(mat), len(mat[0])
visited = [[False] * n for row in range(m)]
q = deque()
destinations = set()

def should_visit(row, col):
    """Return true if (row,col) is a valid position not processed yet"""
    return 0 <= row < m and 0 <= col < n and \
           mat[row][col] != 'o' and not visited[row][col]

for r in range(m):
    for c in range(n):
        if mat[r][c] == 'r':
            q.append((r, c))
            visited[r][c] = True
        elif mat[r][c] == 'b':
            destinations.add((r, c))

dist = 1  # the level in breadth-first-search.
while q:
    for _ in range(len(q)):
        (r, c) = q.popleft()

        for (new_r, new_c) in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
            if should_visit(new_r, new_c):
                if (new_r, new_c) in destinations:
                    return dist
                q.append((new_r, new_c))
                visited[new_r][new_c] = True
    dist += 1

你得到那个异常是因为你使用 foreach 循环队列。 foreach 的内部迭代器将抱怨 queue.removeFirst() 调用。

使用 while (!queue.isEmpty()) { var cell = queue.removeFirst(); 就可以了。我不认为 foreach 循环应该存在。