整体思路:利用邻接矩阵将北京地铁线路图存储,利用Floyd算法求出所有站点间的最短路径。
本题要求的是,查询两点间的线路时换乘线路最少,本算法求得的是经过站点最少的线路,虽然不是严格符合题目要求,但是在绝大部分情况下经过站点最少的线路同样是换成线路最少。
两站查询效果如下:
![img](/i/l/?n=23&i=blog/2909356/202303/2909356-20230319183434794-428742348.png)
本系统的主要代码如下:
```java
package com.example.subwayUtil;
import java.util.ArrayList;
import java.util.List;
public class Floyd {
private static final int max = 99999;
private int[][] path; //最短路径
private int[][] distance; //最短距离
//Floyd算法求最短路径
public Floyd(int[][] Graph){
this.path = new int[Graph.length][Graph.length];
this.distance = new int[Graph.length][Graph.length];
for(int i = 0; i < Graph.length; i++)
for(int j = 0; j < Graph.length; j++) {
this.path[i][j] = j;
this.distance[i][j] = Graph[i][j];
this.distance[j][i] = Graph[j][i];
}
for(int k = 0; k < Graph.length; k++)
for(int i = 0; i < Graph.length; i++)
for(int j = 0; j < Graph.length; j++)
if(this.distance[i][j] > this.distance[i][k] + this.distance[k][j]) {
this.distance[i][j] = this.distance[i][k] + this.distance[k][j];
this.path[i][j] = this.path[i][k];
}
}
//查找最小距离
public int SearchMin(int i, int j){
return this.distance[i][j];
}
public static int getMax() {
return max;
}
public int[][] getPath() {
return path;
}
public void setPath(int[][] path) {
this.path = path;
}
public int[][] getDistance() {
return distance;
}
public void setDistance(int[][] distance) {
this.distance = distance;
}
//将最短距离的站点下标加入到列表中
public List<Integer> printPath(int i, int j){
List<Integer> list = new ArrayList<>();
while(i != j){
System.out.println(i + " " + j);
list.add(i);
i = this.path[i]