Trees and graphs · A level · OCR H446 2.3.1, AQA 7517 4.3.1.1 · about 25 min
Going deep and backtracking, recursively and with a stack; tracing it and what it is used for.
[1 mark]Which data structure does an iterative depth-first traversal use?
[1 mark]An undirected graph has the edges A-B, A-C and B-D. Put the vertices in the order a depth-first traversal from A visits them, trying neighbours in alphabetical order.
Number the lines 1 to 4 to put them in the right order.
CDAB[1 mark]Which application does AQA's specification give for depth-first search?
[1 mark]What does this program print?
GRAPH = {"P": ["Q", "S"], "Q": ["P", "R"], "R": ["Q", "S"], "S": ["P", "R"]}
visited = []
def dfs(v):
visited.append(v)
for n in GRAPH[v]:
if n not in visited:
dfs(n)
dfs("P")
print(" ".join(visited))
[1 mark]Why does a depth-first traversal mark vertices as visited?
The graph in GRAPH is undirected and stored as an adjacency list: each vertex's neighbours, in the order to try them. Write a function dfs that traverses the graph depth-first from a start vertex, recursively or with your own stack, and records the order in which the vertices are visited. Try the neighbours in the order the list gives them. Print DFS order: followed by the vertices in the order visited from A, separated by single spaces. Then print not reachable: followed by every vertex that was never visited, in alphabetical order, separated by single spaces.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
GRAPH = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
"G": ["H"],
"H": ["G"],
}
visited = []Plan your program here, then type it in and press Run.
dfs also count the edges it follows to reach a new vertex. How does the count compare with the number of vertices visited, and why?has_path(start, goal) that stops as soon as goal is visited, and returns True or False.