DSAVisualiseData Structures & Algorithms Studio
Chapter 08 · shortest-path

Paths & Grids

Grid topologies represent 2D cellular worlds with orthogonal and diagonal connectivity. Shortest path search on grids translates Dijkstra algorithm and BFS into coordinate matrices with terrain costs, waterlines, toroidal wraparound boundaries, and multi-source spreads.

Key Invariants & Rules

  • Flat index translation: index = row · cols + col; row = floor(index / cols); col = index % cols.
  • Dijkstra priority queue orders frontier nodes by cumulative distance distTo[v].
  • Toroidal wrapping computes neighbor coordinates modulo grid dimensions: (r + dr + R) % R.
  • Flood fill labels all reachable dry/open cells within the same connected component.
  • Edge relaxation updates distTo[w] = distTo[v] + weight(v,w) whenever a strictly shorter path is found.

Must-Know Algorithms

Grid BFS Maze SolverO(R·C) time and space

Explores orthogonal neighbors to find unweighted shortest escape route.

Dijkstra Mine ClimbingO(R·C log(R·C)) time

Searches weighted terrain grids with elevation difference costs.

Multi-Exit EvacuationO(R·C log(R·C)) time

Directs every cell to its nearest exit via reverse multi-source Dijkstra.

Learning Path (7 Lessons)

Self-Check & Concept Review

1. When mapping a 2D grid cell (row, col) with C columns to a 1D array index, what formula is used?

Row-major 1D indexing multiplies row by the number of columns and adds the column offset.

2. Why does standard BFS find the shortest path in an unweighted grid maze, whereas DFS does not?

Uniform edge costs mean level-by-level queue expansion reaches any reachable cell along the minimal number of edges.

3. In a toroidal grid world (e.g. Mine Climbing), how are neighbor coordinates evaluated across the left boundary?

Toroidal topology connects opposing boundaries; adding dimension length before modulo prevents negative index wrapping.

4. In Dijkstra algorithm on weighted grids, when is a node considered finalized?

Because edge weights are non-negative, polling the minimal distance entry from the priority queue guarantees no shorter path to that node can exist.

5. What does flood fill compute on a binary island grid (e.g. Global Warming)?

Flood fill visits all contiguous orthogonal neighbors satisfying a condition (elevation > water level) and assigns a common component label.