each town struct, we add int distance bool visited set all distances to inf start.distance = 0; Q.enqueue(start); while Q.not empty() { here = Q.dequeue(); here.visited = true if here == dest break; for i = 0 to #exits-1 road r = here.exits[i]; town there = r.goesto if there.distance != inf continue there.distance = here.distance + 1 Q.enqueue(there) ------------------------------------------- Data Structure = a Priority Queue conatins items (anything/towns) + estimated time of arrival (ETA) Operations: create empty (constructor) add new item with its priority change priority of existing item remove item with lowest ETA start.ETA = 0 PQ.add(start) while (true) here = PQ.remove_smallest() here.visited = true if (here==dest) break; for i = 0 to #EXITS-1 r = here.exit[i] there = r.goesto if there.visited continue timethere = here.eta + r.length if there.eta = inf PQ.add(there) else if timethere < there.eta PQ.update(there, timethere); PQ implementations ------------------ Linked list (unordered) remove_smallest = search entire LL for item with min ETA, O(N) add = insert wherever is easiest, O(1) update = search entire LL for item, change its ETA, O(N) Linked list (ordered by ETA, smallest first) remove_smallest = remove from front, O(1) add = search for right place and add there, O(N) update = search for it, change eta, and re-add it, O(N) Tree ordered by ETA remove_smallest = search, delete, O(log N) add = normal tree insertion, O(log N) update = search whole tree to find town, O(N) Adding to a heap ---------------- A, eta = 55 B, eta = 68 C, eta = 40 D, eta = 72 E, eta = 45 F, eta = 21 F21 E45 A55 D50 E47 B68 C58 G52 H66 real way to remove smallest swap smallest(top) with last (bottom right) remove last H66 E45 A55 D50 E47 B68 C58 G52 Moved thing is at the top if moved thing has > eta than top of either subtree swap them and repeat