Planning · University · about 35 min
Cells are nodes, neighbours are edges, and breadth first search is the shortest path when every step costs the same.
[1 mark]What does this program print?
rows = ["S..#",
".#.#",
"...G"]
H, W = len(rows), len(rows[0])
start, goal = (0, 0), (2, 3)
came = {start: None}
queue = [start]
expanded = 0
while queue:
cur = queue.pop(0)
expanded += 1
if cur == goal:
break
r, c = cur
for nxt in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
nr, nc = nxt
if 0 <= nr < H and 0 <= nc < W and rows[nr][nc] not in "#" and nxt not in came:
came[nxt] = cur
queue.append(nxt)
steps, cur = 0, goal
while came[cur] is not None:
cur = came[cur]
steps += 1
print(steps, expanded)
[1 mark]Breadth first search is run on an eight-connected grid. What is wrong with the path it returns?
[1 mark]On the U9 grid (5 cm cells), a four-connected path runs from cell (6, 6) to cell (34, 34) with no detours. How long is it, in cm?
[1 mark]In the breadth first code, the dictionary came does two jobs. What are they?
[1 mark]On the U9 grid, what is the x coordinate, in cm, of the centre of cell (13, 20)?
[1 mark]The cell size is made much larger and breadth first now reports no route across the mat. Why?
Build the grid, run breadth first from cell (6, 6) to cell (34, 34) with four neighbours, and print steps:, how many moves long the path is, and expanded:, how many cells came off the front of the queue before the goal did.
from bugbot import * connect() CELL = 5.0 N = 40 INFLATE = 8.0 WALLS = [(70.0, 0.0, 8.0, 115.0), (125.0, 85.0, 8.0, 115.0)]
Plan your program here, then type it in and press Run.