CASE STUDY 03 · ADVANCED DATA STRUCTURES

Advanced Weighted Graph + Dijkstra

Campus Route Planner

Find the shortest walking route across a campus, reconstruct the complete path and respond correctly when roads are closed or reopened.

01 · PROBLEM DEFINITION

A map becomes useful when it can answer a route question

A student at the Main Gate wants to reach the Innovation Lab. Several walkways are available, and the route with the fewest edges may not have the least distance. Construction can also close a road temporarily, so the best route must be calculated from the current network rather than stored permanently.

The program models locations as vertices and bidirectional walkways as weighted edges. The edge weight is distance in metres. Given a starting location and destination, it must compute the minimum total distance and print every location on that path.

Safety boundary: This educational planner uses distance only. Real navigation also considers accessibility, lighting, opening times, stairs, crowding and emergency restrictions.

Network

Seven named campus locations connected by roads.

Cost

Each open road has a positive distance.

Change

Closing a road removes both directions immediately.

02 · REQUIREMENTS

Define observable behaviour before coding

OperationPreconditionPostcondition
Find routeTwo valid locationsPrint shortest path and total metres, or report unreachable
Close roadAn open direct edge existsBoth matrix directions become INF
Open/update roadDifferent vertices; positive distanceBoth matrix directions store the new weight
Display networkNonePrint each undirected road exactly once

Design assumptions

  • All walkways are bidirectional, so the matrix is symmetric.
  • Every valid edge weight is positive; zero appears only on the diagonal.
  • The graph is small enough for an adjacency matrix and O(V²) Dijkstra.
  • A closed or absent edge uses INF, not weight zero.
  • Location names are stable and their indices are the program’s vertex identifiers.
03 · STRUCTURE SELECTION

Represent the campus as a weighted undirected graph

Vertex: campus location
Edge: direct open walkway
Weight: walking distance in metres
distance[u][v] = distance[v][u]

An adjacency matrix gives constant-time edge lookup and makes road updates direct. It stores V² entries even when only a few roads exist. This is acceptable for seven locations and keeps the algorithm visible to learners.

RepresentationEdge lookupNeighbour scanBest fit
Adjacency matrixO(1)O(V)Small or dense graphs; chosen here
Adjacency listO(degree) typicalO(degree)Large sparse graphs
Edge listO(E)O(E)Algorithms that process all edges, such as Kruskal

Three arrays used by Dijkstra

  • best[v]: smallest known distance from source to v.
  • visited[v]: whether v’s minimum distance has been finalised.
  • previous[v]: predecessor that produced the current best distance; used to reconstruct the path.
04 · CORRECTNESS INVARIANTS

Conditions that must remain true

  1. The diagonal remains zero: travelling from a vertex to itself has no cost.
  2. For this undirected graph, distance[u][v] == distance[v][u].
  3. An unavailable edge is represented by INF in both directions.
  4. Every finite non-diagonal edge weight is strictly positive.
  5. When a vertex becomes visited, its best value is final under Dijkstra’s non-negative-weight assumption.
  6. If previous[v] = u, then u was on the best known route used to update v.
  7. A destination is unreachable exactly when its final best value remains INF.
Critical limitation: Dijkstra’s greedy finalisation is not correct with negative edge weights. Use Bellman–Ford when negative edges are possible, and separately detect negative cycles.
05 · ALGORITHM DESIGN

Relaxation improves routes one edge at a time

Initialise every best distance to INF, except the source which is zero. Repeatedly select the unvisited vertex with the smallest best value. For each neighbour, evaluate a route that first reaches the current vertex and then crosses the edge.

candidate = best[current] + weight(current, neighbour)
if candidate < best[neighbour]:
    best[neighbour] = candidate
    previous[neighbour] = current

The comparison is called relaxation. It does not immediately prove the neighbour is final; it records a better known route. Finalisation happens when that neighbour later becomes the minimum unvisited vertex.

Path reconstruction

Starting from the destination, follow previous until -1. This produces the path backwards, so store vertices in a temporary array and print them in reverse order. Distance alone cannot reconstruct the route; the predecessor relationship is essential.

Initialise
Select nearest
Relax neighbours
Reconstruct path
06 · COMPLETE IMPLEMENTATION

Compiler-ready C11 program

programs/campus-route-planner.c
Open Compiler
Loading source…

Implementation reading order

Graph state

Read initialization, connect and sample-road loading.

Shortest path

Trace nearestUnvisited, relaxation and printPath.

Live updates

Verify road closure and reopening update both directions.

INF is defined below INT_MAX so adding a practical edge to a finite route does not overflow. The relaxation expression is reached only when the current vertex has a finite best distance.

07 · INTERACTIVE TRACING

Trace Main Gate to Innovation Lab

  1. Initialise source at Main Gate.
  2. Finalise Main Gate.
  3. Finalise Admin Block.
  4. Finalise Library.
  5. Finalise CSE Block.
  6. Finalise Innovation Lab.
  7. Reconstruct path.
  8. Display result.
Current state

Press Next to begin.

What if Admin–Library closes? The former 360 m route disappears. The algorithm works on the updated matrix and selects another valid route; it does not reuse a stale answer.
08 · TEST DESIGN

Test cost, connectivity and updates

Test 1 — Known shortest path
Main Gate to Innovation Lab must use Gate → Admin → Library → Lab for 360 m in the original graph.
Test 2 — Source equals destination
Library to Library must print Library with total distance 0. No edge is required.
Test 3 — Road closure changes result
Close Admin–Library, calculate again and verify the result avoids that edge while remaining minimal among open roads.
Test 4 — Unreachable destination
Close every road connected to Sports Complex. A route to it must report unavailable rather than print INF as a distance.
Test 5 — Symmetric update
Update Library–Lab to 50 m. Both Library-to-Lab and Lab-to-Library searches must observe the same edge cost.
Test 6 — Invalid input
Reject location 0, location 8, a self-road and non-positive road distances without modifying the graph.
09 · COMPLEXITY

Complexity depends on representation

OperationCurrent implementationAlternativeReason
DijkstraO(V²)O((V+E) log V)Linear minimum selection vs binary heap with adjacency list
Road lookup/updateO(1)O(degree) list scanDirect matrix indexing
Display roadsO(V²)O(V+E)Scan upper triangle vs list entries
Path reconstructionO(V)O(V)A simple path contains at most V vertices
Graph storageO(V²)O(V+E)Full matrix vs sparse adjacency list

For a small campus, clarity and constant-time updates make the matrix reasonable. For a national road network, an adjacency list plus priority queue is far more appropriate.

10 · PRACTICE

Check the route-planning logic

Which array is required to print the route, not just its distance?

Which algorithm should replace Dijkstra if negative edge weights are allowed?

Extension challenges

  1. Replace the matrix with adjacency lists and use a binary min-heap.
  2. Support directed one-way walkways and identify which invariants change.
  3. Offer “shortest distance” and “least walking time” as different cost modes.
  4. Compute alternative routes that do not share the same critical edge.
  5. Add A* search with coordinates and an admissible straight-line heuristic.
11 · INTERVIEW PREPARATION

Defend the algorithm and its limits

Why does Dijkstra require non-negative weights?

It permanently finalises the smallest unvisited distance. A later negative edge could create a cheaper path to an already finalised vertex, invalidating that greedy decision.

Why not use breadth-first search?

BFS minimises the number of edges only when edges are unweighted or have equal cost. Campus roads have different distances, so fewer roads does not necessarily mean fewer metres.

When is Floyd–Warshall preferable?

When routes between many or all pairs are repeatedly required and O(V³) preprocessing plus O(V²) storage is acceptable. Dynamic closures would require recomputation or more advanced handling.

How does a priority queue improve Dijkstra?

It retrieves the smallest tentative distance in logarithmic time instead of scanning all vertices. With adjacency lists this yields O((V+E) log V) for a binary heap.

What changes for a directed graph?

Opening u→v no longer implies v→u. The symmetry invariant is removed, updates touch one direction unless explicitly requested, and reachability can differ by travel direction.

12 · KEY TAKEAWAY

The shortest path is a claim supported by maintained state

The graph represents what movement is currently possible; Dijkstra maintains the best known costs; the predecessor array explains how the answer was obtained. Correct routing requires all three, along with an explicit non-negative-weight assumption.