写一个北京地铁两个站点之间最短换乘的Java代码
时间: 2023-05-13 16:07:27 浏览: 121
以下是一个基于Dijkstra算法的Java代码,用于计算北京地铁两个站点之间的最短换乘路线:
```java
import java.util.*;
public class Subway {
private Map<String, List<String>> lines; // 地铁线路图
private Map<String, List<String>> stations; // 地铁站点信息
private Map<String, Map<String, Integer>> connections; // 地铁站点之间的连接信息
public Subway() {
lines = new HashMap<>();
stations = new HashMap<>();
connections = new HashMap<>();
// 初始化地铁线路图、站点信息和连接信息
// 省略代码
}
public List<String> shortestPath(String start, String end) {
Map<String, Integer> distances = new HashMap<>(); // 记录起点到各个站点的距离
Map<String, String> previous = new HashMap<>(); // 记录每个站点的前一个站点
PriorityQueue<String> queue = new PriorityQueue<>(Comparator.comparingInt(distances::get)); // 用于存储未处理的站点
// 初始化距离和前置节点信息
for (String station : stations.keySet()) {
distances.put(station, Integer.MAX_VALUE);
previous.put(station, null);
}
distances.put(start, 0);
// 将起点加入队列
queue.offer(start);
while (!queue.isEmpty()) {
String current = queue.poll();
if (current.equals(end)) {
break;
}
for (String neighbor : connections.get(current).keySet()) {
int distance = distances.get(current) + connections.get(current).get(neighbor);
if (distance < distances.get(neighbor)) {
distances.put(neighbor, distance);
previous.put(neighbor, current);
queue.offer(neighbor);
}
}
}
// 构建最短路径
List<String> path = new ArrayList<>();
String current = end;
while (current != null) {
path.add(0, current);
current = previous.get(current);
}
return path;
}
}
```
使用方法:
```java
Subway subway = new Subway();
List<String> path = subway.shortestPath("西二旗", "天安门东");
System.out.println(path); // [西二旗, 生命科学园, 朱辛庄, 育知路, 平西府, 回龙观东大街, 霍营, 霍营, 立水桥, 立水桥南, 通州北苑, 果园,
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)