Programming, problem solving, and algorithms

CPSC 203, 2026 W1

November 24, 2026

Announcements

  • Project 3 (Campus Walks) due Monday December 7.
    • You can get started after this lecture.
  • This week: Lab 10 (algorithm complexity) and POTW 10 (permutations) due Sunday Nov 29.
  • Practice Examlet 5 is available.
    • Examlet 5 window is Thursday December 3 to Monday December 7 (after last lecture).
  • Feeling overwhelmed? You are not alone!

Finishing Dijkstra’s Algorithm for SSSP

Dijkstra’s Algorithm: Complexity

  • Analysis is very similar to that for BFS / DFS:
    • Each node enters the queue a bounded number of times (for Dijkstra: bounded by the number of neighbours).
    • Each time it enters the queue, we need to do a constant amount of work (for Dijkstra: essentially nothing).
    • Each time it exits the queue, we need to do a constant amount of work (for Dijkstra: for each neighbour, check whether there is a better path).

Reminder: BFS / DFS Complexity

  • For BFS and DFS, we used a FIFO queue and a LIFO queue (stack) respectively.
    • For FIFO or LIFO queue the work needed to add or remove a item is constant (does not depend on the number of items in the queue).
  • Assume: \(n\) is the number of nodes in the graph and the maximum number of neighbours is bounded by a constant (it does not depend on \(n\)).
    • BFS / DFS: For \(O(n)\) times, do work \(O(1 + 1 + 1 + 1)\) (work when entering the queue, work of entering the queue, work of exiting the queue, work when exiting the queue)
    • BFS / DFS: Total cost \(O(n)\).

Dijkstra’s Algorithm: Complexity

  • However, a priority queue takes more work to maintain than a FIFO or LIFO queue.
    • For a priority queue containing \(n\) items, the work needed to add or remote an item is \(O(\lg n)\) (that work is done to keep track of the item with smallest current priority).
  • Assume: \(n\) is the number of nodes in the graph and the maximum number of neighbours is bounded by a constant (it does not depend on \(n\)).
    • Dijkstra: For \(O(n)\) times, do work \(O(1 + \lg n + \lg n + 1)\) (work when entering the queue, work of entering the queue, work of exiting the queue, work when exiting the queue)
    • Dijkstra: Total cost \(O(n \lg n)\).

Travelling Salesperson Problem (TSP)

Maps: Running Errands

  • You’ve got six errands to run. What order do you do them in?
  • Determine the least cost route through a set of given locations.

Travelling Salesperson Problem (TSP)

“Given a list of cities, and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?”

  • Classic problem on graphs.
  • No efficient (eg: polynomial time) algorithmic solution is known.
    • No efficient way to tell if an answer is the best possible one!
  • Efficient sub-optimal versions exist; for example,
    • Restricted classes of graphs.
    • Almost optimal solutions.
    • Probabilistically optimal solutions.

Why is the problem so hard?

  • How many different candidate solutions are there for six locations?
  • Generalize to k locations?

Possible solutions

“Solving” TSP in Practice: A Blog Adventure

https://medium.com/data-science/around-the-world-in-90-414-kilometers-ce84c03b8552

Why This Matters

There are lots of applications:

  • 📦 UPS/FedEx/Amazon Delivery: Millions saved by reducing even 1km per driver per day.
  • 🍔 UberEats/DoorDash/Skip: Multi-stop pickup/delivery with time windows.
  • 🚌 School Bus Routing: Minimize buses, fuel, and time while meeting constraints.
  • ❄️ Snowplow & Garbage Truck Routing: Efficiently cover every street in a city.
  • ✈️ Airline Crew Scheduling: Complex daily routing: crews must return to base, meet rest rules.
  • 🌍 City Infrastructure Planning: Utility inspections, meter reading, streetlight repair routes.
  • 🚑 Ambulance & Emergency Routing: Minimize response times; life-critical optimization.
  • 🏭 Factory Robots & CNC Machines: Optimizing tool paths reduces waste, heat, and wear.
  • 🧪 Medical Lab Sample Pipelines: Robotic arms schedule efficient multi-station workflows.
  • 🧬 DNA Sequencing & Genome Assembly: Ordering fragments relies on TSP-like reconstruction.

Plan for Code

Steps to assemble our solution:

  1. assemble the graph and errands
  2. create pairwise distances
  3. create all possible permutations of paths
  4. find minimum route and assemble turn-by-turn for that route
  5. visualize on map


Identifying the Errands

Consider some Vancouver landmarks:

  • PNE
  • Queen E Park
  • Timmy’s
  • ESB at UBC

https://www.openstreetmap.org/

Create pairwise distances

How do we find it? SSSP!

  • example:
path['Vancouver']['Bellingham'] = nx.shortest_path(G, 'Vancouver', 'Bellingham', weight='length')

How should we store it? Many possible options…

  • example:
dist['Vancouver']['Bellingham'] -> int
path['Vancouver']['Bellingham'] -> list

Create all possible orders

For a collection of items, find all possible ordering permutations.

  • For locations A, B, C and D we could have:
ABCD ABDC ACBD ACDB ADBC ADCB
BACD BADC BCAD BCDA BDAC BDCA
CABD CADB CBAD CBDA CDAB CDBA
DABC DACB DBAC DBCA DCAB DCBA

Fortunately, Python has a function for that:

tours = list(itertools.permutations(list(dferrands['node'])))

Tour Distance

Consider the example tour [A,D,B,E,F,C]

What pairs of locations will we consider for a given order?

How do we find the total distance if we do the errands in the suggested order?


Aside: Adding a New Column to the gdf

Goal: Create a new column latlong containing coordinates for each errand in the dataframe.

dferrands['latlong'] = dferrands.apply(lambda row: ox.geocode(row['errand']), axis=1)
  • df.apply(..., axis=1): Run a function once for each row to create a new series.

  • lambda row: ox.geocode(row['errand']): An anonymous function.

    • Given a row: Look up the place name in row['errand'], geocode it, and return the (lat, lon).
  • dferrands['latlong'] = ...: Assign the returned series as a new column named latlong.

Why lambda? We only need this function once, so we write it inline.

Demo

Launch Class Activity: Traveling Salesperson in PrairieLearn.

You will complete four functions:

  • compute_pairwise(G, nodes): build a table of driving distances between every pair of errand locations.
  • tourlength(tour, dfdist): compute the total round-trip distance for a given visit order.
  • find_best_tour(tours, dfdist): search all permutations and return the shortest tour.
  • assemble_route(tour, dfdict): stitch together the full turn-by-turn road sequence using pre-computed paths.

TSP vs SSSP Summary

Aspect SSSP (Single-Source Shortest Paths) TSP (Travelling Salesperson)
Goal Shortest route from one source vertex to every other vertex One cheapest tour visiting all vertices and returning
Shape Tree of paths from the source Cycle through all vertices
Must visit all? No – each path can skip most vertices Yes – must visit every vertex exactly once
Overlap Paths often share edges Tour is one path (which might backtrack)
Difficulty Fast exact algorithms exist (such as Dijkstra) NP-hard; exact solution is hard for large graphs