Для создания программы по расчету минимального пути между станциями метрополитена Санкт-Петербурга, можно использовать алгоритм Дейкстры. Для начала потребуется представление графа метрополитена в виде списка соседств или матрицы смежности, затем применить алгоритм к этой структуре для нахождения кратчайшего пути. Но учтите, что здесь будет только реализация алгоритма без реальных данных о станциях и их связях.
import java.util.*;
class MetroGraph {
private final int noOfStations;
private final HashMap<String, Integer> stationIndexMap;
private final String[] stationNames;
private final List<List<Node>> adjList;
public MetroGraph(int noOfStations) {
this.noOfStations = noOfStations;
this.stationIndexMap = new HashMap<>();
this.stationNames = new String[noOfStations];
this.adjList = new ArrayList<>();
for (int i = 0; i < noOfStations; i++) {
adjList.add(new ArrayList<>());
}
}
public void addStation(String stationName, int index) {
stationIndexMap.put(stationName, index);
stationNames[index] = stationName;
}
public void addEdge(String source, String destination, int distance) {
int sourceIndex = stationIndexMap.get(source);
int destIndex = stationIndexMap.get(destination);
adjList.get(sourceIndex).add(new Node(destIndex, distance));
adjList.get(destIndex).add(new Node(sourceIndex, distance)); // If bi-directional
}
public void calculateShortestPathFromSource(String sourceStation) {
int sourceIndex = stationIndexMap.get(sourceStation);
int[] distances = new int[noOfStations];
Arrays.fill(distances, Integer.MAX_VALUE);
distances[sourceIndex] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingInt(node -> node.cost));
pq.add(new Node(sourceIndex, 0));
while (!pq.isEmpty()) {
Node node = pq.poll();
int stationIndex = node.stationIndex;
int currentDistance = node.cost;
for (Node adjacent : adjList.get(stationIndex)) {
int adjacentIndex = adjacent.stationIndex;
int edgeWeight = adjacent.cost;
if (currentDistance + edgeWeight < distances[adjacentIndex]) {
distances[adjacentIndex] = currentDistance + edgeWeight;
pq.add(new Node(adjacentIndex, distances[adjacentIndex]));
}
}
}
System.out.println("Shortest paths from " + sourceStation + ":");
for (int i = 0; i < distances.length; i++) {
System.out.println("To " + stationNames[i] + " : " + distances[i]);
}
}
static class Node {
int stationIndex;
int cost;
Node(int stationIndex, int cost) {
this.stationIndex = stationIndex;
this.cost = cost;
}
}
}
public class MetroPathFinder {
public static void main(String[] args) {
// Example usage with 5 hypothetical stations
MetroGraph graph = new MetroGraph(5);
graph.addStation("StationA", 0);
graph.addStation("StationB", 1);
graph.addStation("StationC", 2);
graph.addStation("StationD", 3);
graph.addStation("StationE", 4);
graph.addEdge("StationA", "StationB", 3);
graph.addEdge("StationB", "StationC", 4);
graph.addEdge("StationA", "StationD", 7);
graph.addEdge("StationD", "StationE", 5);
graph.addEdge("StationC", "StationE", 6);
graph.addEdge("StationB", "StationD", 1);
// Starting the path calculation from "StationA"
graph.calculateShortestPathFromSource("StationA");
}
}
Обратите внимание, что для упрощения примера, используются вымышленные станции и расстояния между ними. Также алгоритм не учитывает временные затраты на пересадки и прочие реалистические аспекты метрополитена. В реальном приложении потребуется подробные и точные данные о структуре метрополитена, их связях и времени между станциями для корректного расчета минимального пути.