Practice Discrete Math

Algorithms / Shortest Path Modeling

Least You Need to Know: Shortest-Path Modeling and State Graph Design

Many interview and contest problems become easier once you model them as shortest-path problems. The art is to choose the right state graph: vertices represent states or positions, edges represent allowed moves, and weights represent transition cost. Once the model is correct, the algorithm choice follows from the edge weights.

The least you need to know

Key notation

state graph graph whose vertices represent problem states and edges represent legal moves
super-source an extra source connected to multiple initial states
transition cost the weight associated with one allowed move

Tiny worked example

  • In a grid, each cell can be a vertex.
  • Legal moves to neighboring cells become edges.
  • If each move costs 1, BFS solves the shortest-path problem.
  • If terrain costs vary, edge weights model those costs and a weighted shortest-path algorithm is needed.

Common mistakes

How to recognize this kind of problem

Start practice