Skip to content
Java project #22Advanced

Metro Route Finder

Model a metro network of named lines and find the fastest route (Dijkstra over station-and-line states with interchange penalties) or the route with the fewest stops (BFS).

Estimated time
~7 hours to build
Files
5 files · 381 lines
Technologies
Java 21, PriorityQueue, ArrayDeque, Records, Optional

Introduction

Journey planners must weigh more than distance: changing lines takes time. Searching over (station, line) pairs instead of stations lets Dijkstra's algorithm charge a penalty exactly when a journey switches lines, and the resulting path can be presented as legs on each line.

Problem statement

Let users define metro lines as alternating station names and travel times, list lines and interchanges, and ask for the fastest route between two stations (with a 5-minute penalty per change) or the route with the fewest stops. Present routes as legs per line with stop counts, the number of changes and the total time, and compute distance-based fares. Reject invalid line definitions, unknown stations and identical start and end.

Objectives

  • Search over an expanded state space (station, line)
  • Implement Dijkstra with a priority queue and stale-entry skipping
  • Implement BFS for unweighted shortest paths
  • Reconstruct and group paths into journey legs

Features

  • Lines defined at run time with validation
  • Fastest route with interchange penalties
  • Fewest-stops route
  • Legs, changes, total time and fares

Concepts demonstrated

  • Graphs
  • Dijkstra's algorithm
  • Breadth-first search
  • State-space search
  • Path reconstruction

System architecture

MetroNetwork stores an adjacency list of Edge(to, line, minutes). fastest runs Dijkstra over State(station, line): moving along an edge costs its minutes, plus the penalty if the edge's line differs from the state's line. fewestStops is a BFS that prefers staying on the current line. build walks the predecessor map back from the destination, sums minutes and penalties, and groups consecutive steps on the same line into Legs.

Folder structure

TextProject tree
metro-route-finder/
├── README.md
├── src/Main.java
├── src/MetroNetwork.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

60 lines
Javasrc/Main.java
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
/**
* Metro Route Finder — define metro lines, then ask for the fastest route (Dijkstra with a
* 5-minute interchange penalty) or the route with the fewest stops (BFS), with journey legs.
*
* Commands:
* line NAME STATION MIN STATION MIN STATION ... lines interchanges
* fastest FROM TO fewest FROM TO fare FROM TO quit
*/
public class Main {
public static void main(String[] args) {
MetroNetwork metro = new MetroNetwork(5);
Scanner in = new Scanner(System.in);
System.out.println("=== Metro Route Finder === (changing lines costs 5 minutes)");
while (true) {
System.out.print("> ");
if (!in.hasNextLine()) break;
String[] p = in.nextLine().trim().split("\\s+");
System.out.println();
try {
switch (p[0].toLowerCase()) {
case "line" -> {
metro.addLine(p[1], Arrays.asList(p).subList(2, p.length));
List<String> st = metro.lines().get(p[1]);
System.out.println("Line " + p[1] + ": " + st.size() + " stations, " + st.get(0) + " - " + st.get(st.size() - 1));
}
case "lines" -> metro.lines().forEach((name, st) -> System.out.println(" " + name + ": " + String.join(" - ", st)));
case "interchanges" -> System.out.println(" " + String.join(", ", metro.interchanges()));
case "fastest", "fewest" -> {
Optional<MetroNetwork.Route> r = p[0].equalsIgnoreCase("fastest") ? metro.fastest(p[1], p[2]) : metro.fewestStops(p[1], p[2]);
if (r.isEmpty()) System.out.println("No route between " + p[1] + " and " + p[2]);
else print(r.get());
}
case "fare" -> {
MetroNetwork.Route r = metro.fewestStops(p[1], p[2]).orElseThrow(() -> new IllegalStateException("no route"));
int fare = r.stops() <= 2 ? 10 : r.stops() <= 5 ? 20 : r.stops() <= 9 ? 30 : 40; // distance-based slabs
System.out.println("Fare " + p[1] + " -> " + p[2] + ": Rs " + fare + " (" + r.stops() + (r.stops() == 1 ? " stop)" : " stops)"));
}
case "quit" -> { return; }
default -> System.out.println("Commands: line lines interchanges fastest fewest fare quit");
}
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
System.out.println("Error: missing or invalid arguments");
} catch (IllegalArgumentException | IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
static void print(MetroNetwork.Route r) {
for (MetroNetwork.Leg leg : r.legs())
System.out.println(" " + leg.line() + ": " + String.join(" -> ", leg.stations()) + " (" + (leg.stations().size() - 1) + " stop" + (leg.stations().size() == 2 ? "" : "s") + ")");
System.out.println(" " + r.stops() + " stops, " + r.changes() + " change(s), about " + r.minutes() + " min");
}
}

What each file does

src/MetroNetwork.java
Lines and edges, Dijkstra over (station, line) states, BFS, interchanges and route building.
src/Main.java
The command loop, fares and route printing.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Metro Route Finder === (changing lines costs 5 minutes)
>
Line Purple: 8 stations, Whitefield - Kengeri
>
Line Green: 8 stations, Nagasandra - Silk
>
Line Yellow: 6 stations, MGRoad - Bommasandra
>
Line Blue: 3 stations, Trinity - Yeshwanthpur
>
Line Pink: 2 stations, Whitefield - Indiranagar
>
Error: travel times must be positive
>
Purple: Whitefield - Indiranagar - Trinity - MGRoad - Cubbon - Majestic - Vijayanagar - Kengeri
Green: Nagasandra - Yeshwanthpur - Malleshwaram - Majestic - Chickpet - KRMarket - Jayanagar - Silk
Yellow: MGRoad - Richmond - Lalbagh - Jayanagar - BTM - Bommasandra
Blue: Trinity - Ulsoor - Yeshwanthpur
Pink: Whitefield - Indiranagar
>
Indiranagar, Jayanagar, MGRoad, Majestic, Trinity, Whitefield, Yeshwanthpur
>
Purple: Indiranagar -> Trinity -> MGRoad (2 stops)
Yellow: MGRoad -> Richmond -> Lalbagh -> Jayanagar (3 stops)
5 stops, 1 change(s), about 20 min
>
Purple: Indiranagar -> Trinity -> MGRoad (2 stops)
Yellow: MGRoad -> Richmond -> Lalbagh -> Jayanagar (3 stops)
5 stops, 1 change(s), about 20 min
>
Purple: Whitefield -> Indiranagar -> Trinity -> MGRoad -> Cubbon -> Majestic -> Vijayanagar -> Kengeri (7 stops)
7 stops, 0 change(s), about 23 min
>
Green: Nagasandra -> Yeshwanthpur -> Malleshwaram -> Majestic -> Chickpet -> KRMarket -> Jayanagar (6 stops)
Yellow: Jayanagar -> BTM (1 stop)
7 stops, 1 change(s), about 33 min
>
Green: Silk -> Jayanagar (1 stop)
Yellow: Jayanagar -> Lalbagh -> Richmond -> MGRoad (3 stops)
Purple: MGRoad -> Trinity -> Indiranagar -> Whitefield (3 stops)
7 stops, 2 change(s), about 34 min
>
Fare Majestic -> Cubbon: Rs 10 (1 stop)
>
Fare Kengeri -> Bommasandra: Rs 30 (7 stops)
>
Error: start and destination are the same
>
Error: unknown station Airport
>
Input
line Purple Whitefield 4 Indiranagar 3 Trinity 2 MGRoad 2 Cubbon 3 Majestic 4 Vijayanagar 5 Kengeri
line Green Nagasandra 6 Yeshwanthpur 4 Malleshwaram 3 Majestic 2 Chickpet 3 KRMarket 4 Jayanagar 5 Silk
line Yellow MGRoad 3 Richmond 4 Lalbagh 3 Jayanagar 6 BTM 5 Bommasandra
line Blue Trinity 2 Ulsoor 3 Yeshwanthpur
line Pink Whitefield 4 Indiranagar
line Broken Alpha 0 Beta
lines
interchanges
fastest Indiranagar Jayanagar
fewest Indiranagar Jayanagar
fastest Whitefield Kengeri
fastest Nagasandra BTM
fewest Silk Whitefield
fare Majestic Cubbon
fare Kengeri Bommasandra
fastest Majestic Majestic
fastest Majestic Airport
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Indiranagar → Jayanagar takes 20 minutes via MG Road (5 + 10 + 5 penalty), beating 24 minutes via Majestic.
  • Silk → Whitefield needs two changes.
  • A line with a 0-minute segment, identical start and end, and the unknown station 'Airport' are rejected.

Common errors

Routes ignore the cost of changing lines

Include the current line in the search state so the penalty can be charged on the edge that switches lines.

Dijkstra returns non-optimal routes

Stop when the destination is polled from the queue, not when it is first discovered, and skip stale queue entries.

Possible improvements

  • Load the network from a file
  • Add walking transfers between nearby stations
  • Show departure times using a timetable

Additional challenges

  1. 1Find the route with the fewest changes, then the fastest among those.
  2. 2Close a station and reroute.
  3. 3Compute the station that is most central (smallest average travel time).

Built and tested it yourself? Mark it to update your dashboard.