Planning · University · about 35 min
When steps cost different amounts, the cheapest route is not the shortest one, and a queue sorted by cost finds it.
[1 mark]What does this program print?
import heapq
EDGES = {"S": [("A", 1), ("B", 2)], "A": [("G", 5)], "B": [("C", 2)], "C": [("G", 1)], "G": []}
best, came, done = {"S": 0}, {"S": None}, set()
queue = [(0, "S")]
while queue:
cost, cur = heapq.heappop(queue)
if cur in done:
continue
done.add(cur)
if cur == "G":
break
for nxt, w in EDGES[cur]:
price = cost + w
if price < best.get(nxt, 1e9):
best[nxt] = price
came[nxt] = cur
heapq.heappush(queue, (price, nxt))
path, n = [], "G"
while n is not None:
path.append(n)
n = came[n]
print(best["G"], "".join(reversed(path)))
[1 mark]In Dijkstra's algorithm, when is a node's cost final?
[1 mark]Why does Dijkstra's algorithm give wrong answers on a graph with a negative edge cost?
[1 mark]With the U9.3 cost map, a robot takes a diagonal step on the 5 cm grid into a cell whose centre is 12 cm from a wall. What does the step cost, to two decimal places?
[1 mark]A cell is already on the queue and a cheaper route to it is found. What do most implementations do?
[1 mark]Adding a clearance penalty to the cost map changed the route to run down the middle of the corridor. What changed in the algorithm?
Same grid as U9.2, now with eight neighbours and the cost map above. Print cost:, the total cost of the cheapest path, and min gap:, the smallest distance from any cell on that path to a wall.
from bugbot import * import heapq import math connect() CELL = 5.0 N = 40 INFLATE = 8.0 NEAR = 20.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.
1 + 4 * max(0, 1 - gap/25). Does the path move further from the walls, or just sit differently?