I have made part of an algorithm below where I need to use a queue, but in Java I can't modify the queue while iterating over it. I get a ConcurrentModificationException
.
What I can I do about this? I've been thinking about this for several hours.
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