Trees and graphs · A level · OCR H446 1.4.2, AQA 7517 4.2.4.1, Eduqas A500QS 1.1 · about 35 min
Model the mat as a graph, find the shortest route with breadth-first search, and drive it.
[1 mark]The robot must reach a square in the fewest moves, and every move costs the same. Why use breadth-first rather than depth-first search?
[1 mark]Why is an adjacency list a good choice for a grid of squares?
[1 mark]A 5 by 5 grid of squares has no blocked squares. Each square is joined to the squares directly above, below, left and right of it. How many edges does the graph have?
[1 mark]What does this program print?
from collections import deque
GRAPH = {"S": ["A", "B"], "A": ["S", "C"], "B": ["S", "D"], "C": ["A", "G"], "D": ["B"], "G": ["C"]}
parent = {"S": None}
queue = deque(["S"])
while queue:
v = queue.popleft()
for n in GRAPH[v]:
if n not in parent:
parent[n] = v
queue.append(n)
route = []
v = "G"
while v is not None:
route.append(v)
v = parent[v]
print(" ".join(reversed(route)))
[1 mark]After a breadth-first search records each vertex's parent, what shape do the parent links form?
GRID is the mat from the brief, with row 0 at the far end of the mat and column 0 on the left, and NAMES gives the letters in reading order. The robot starts in the centre of square A facing up the mat, and square centres are 25 cm apart. Build an adjacency list for the free squares. Print vertices: and the number of free squares, then edges: and the number of edges. Find the route from A to O with the fewest moves, using a breadth-first search that takes squares from the front of a queue with popleft() or pop(0). Print route: followed by the letters of the squares from A to O separated by single spaces, and then moves: followed by the number of moves. Finally drive the route square by square, without touching a blocked square, finishing in O.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
from collections import deque
GRID = ["....",
".##.",
"..#.",
"#..."]
NAMES = "ABCDEFGHIJKLMNOP"
graph = {}Plan your program here, then type it in and press Run.
no route instead of crashing when the goal cannot be reached. Test it by blocking N and P.