Queues in simulations: taking turns, and a first look at BFS
🌍 In real life. The computer lab at school has one printer and three students waiting: Mim has 5 pages, Raju 2 and Tia 3. If Mim goes first and prints everything, Raju waits for all 5 pages just to print 2. So the lab assistant makes a rule: 2 pages per turn, then the job goes to the back of the line if it isn't finished. Short jobs get out quickly instead of waiting for the whole of a long one.
Your phone does this all the time: a few processor cores run dozens of apps by giving each a few milliseconds in turn. This is called round-robin, and its heart is a queue.
The idea in one sentence: in a simulation, a queue holds whatever is waiting its turn; each step takes the front, does one piece of work, and puts it back at the end if there is more to do.
Its words:
- simulation: running a process step by step in code to see what happens
- round-robin: everyone gets a turn of at most the same length, going round and round
- turn (or time slice): the most work one task gets before the next one's turn
Round-robin, step by step:
- put every task in a deque, in order
- take the front task and run it for
min(turn, left)minutes; move the clock on - if it still has work left, append it to the back; otherwise it is finished
- repeat until the deque is empty
Watch the printer give each job 2 pages at a time (here a job's minutes are pages):
Why it is correct. An unfinished task always goes back into the queue, so it gets another turn after everyone ahead of it has had theirs: nothing is lost and everyone keeps moving. Each turn takes at least one minute off the front task, so the simulation ends.
What it costs. A task needing t minutes takes ⌈t / turn⌉ turns (t ÷ turn, rounded up), and each turn is one popleft and at most one append: O(1). So the whole run is O(total turns). Mim, Raju and Tia take 3 + 1 + 2 = 6 turns.
A first look at BFS. A queue also finds the shortest way out of a maze. Drop a stone in a pond: the ripple reaches everything 1 step away first, then 2 steps, then 3. Breadth-first search (BFS) does the same: start with the entrance in a queue; take the front cell, and add each open neighbour you haven't seen yet, one step further. Because cells come out in the order they went in, every cell 1 step away is handled before any cell 2 steps away, so the first time BFS reaches the exit, it has used the fewest steps. Each cell joins the queue at most once: O(rows × cols). You will meet BFS properly in the graphs world.
from collections import deque
def round_robin(tasks, turn):
line = deque(tasks)
clock = 0
finished = []
while line:
name, left = line.popleft()
ran = min(turn, left)
clock += ran
if left > ran:
line.append((name, left - ran)) # back of the line
else:
finished.append((name, clock))
return finished
print(round_robin([("Mim", 5), ("Raju", 2), ("Tia", 3)], 2))from collections import deque
def steps_to_exit(grid):
rows, cols = len(grid), len(grid[0])
start = next((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == "S")
todo = deque([(start, 0)])
seen = {start}
while todo:
(r, c), steps = todo.popleft()
if grid[r][c] == "E":
return steps
for nr, nc in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#" and (nr, nc) not in seen:
seen.add((nr, nc)) # mark it when it joins
todo.append(((nr, nc), steps + 1))
return -1
maze = ["S.#.",
"..#E",
"#...",]
print(steps_to_exit(maze))Mistakes and edge cases.
- in round-robin, taking a full turn even when less is left: the clock runs ahead (
min(turn, left)) - in BFS, marking a cell as seen only when it comes out of the queue: it can join many times, and on big grids the queue explodes
- using a stack (
pop()) instead of a queue in BFS: you still find a way out, but not always the shortest - using
list.pop(0)for the queue: correct, but each step costs O(n) - an exit you can't reach: the queue empties first, so answer -1
Quiz
What does this print?
from collections import deque line = deque([("A", 3), ("B", 1)]) clock, done = 0, [] while line: name, left = line.popleft() ran = min(2, left) clock += ran if left > ran: line.append((name, left - ran)) else: done.append((name, clock)) print(done)Jobs of 5, 2 and 3 minutes take turns of 2 minutes. How many turns are there in all?
- 6
- 5
- 10
Why does BFS find the fewest steps to the exit?
- The queue hands out cells in order of distance, so the exit first comes out at its smallest distance
- It tries every possible path and keeps the shortest
- It always walks towards the exit
This finds a way out, but not always the shortest. Which line is wrong?
from collections import deque def steps_to_exit(grid, start): todo = deque([(start, 0)]) seen = {start} while todo: (r, c), steps = todo.pop() if grid[r][c] == "E": return steps for nr, nc in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]: if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#" and (nr, nc) not in seen: seen.add((nr, nc)) todo.append(((nr, nc), steps + 1)) return -1
Coding tasks
Write
round_robin(tasks, turn)with a deque:tasksis a list of(name, minutes)in line order, and each turn the front task runs for at mostturnminutes, then goes to the back if it isn't finished. Give back a list of(name, finish_minute)in the order the tasks finish, with the clock starting at 0.Write
steps_to_exit(grid)with BFS:gridis a list of equal-length strings with one"S"(start) and one"E"(exit);"#"is a wall and"."is open. Moving up, down, left or right is one step. Give back the fewest steps from S to E, or -1 if E can't be reached.