import java.util.*;
/**
* @Author :
* @description 加权图算最短路径
* @create 2024/3/26 20:09
*/
//城市结点
public class City {
//城市结点名
private String name;
//邻接城市结点散列表
private HashMap<City,Integer> routes = new HashMap<>();
public City(String name) {
this.name = name;
}
//添加邻接城市结点到散列表
public void addRoute(City city,int price){
routes.put(city,price);
}
//获取邻接城市结点散列表
public HashMap<City, Integer> getRoutes() {
return routes;
}
//获取城市结点名
public String getName() {
return name;
}
/**
* dijkstra最短路径算法
* @param start 起点城市
* @param other_cities 其他城市结点
* @return 返回一张散列表,{终点城市:[价格,到达终点前要经过的那个城市]}
*/
public static HashMap<City, Object[]> dijkstra(City start, City[] other_cities){
//散列表
//{终点城市:[价格,到达终点前要经过的那个城市]}
HashMap<City, Object[]> routes_from_city = new HashMap<>();
//从起点城市到起点城市是0元(不要买票)
routes_from_city.put(start, new Object[]{0, start});
//初始化其他城市
for (City c :
other_cities) {
routes_from_city.put(c, new Object[]{Integer.MAX_VALUE, null});//价格暂时设置为”无穷大“
}
//将已访问的城市结点添加到这里
ArrayList<City> visited_cites = new ArrayList<>();
//首先访问起点城市
City currentCity = start;
while (currentCity!=null){
//标记当前城市已被访问
visited_cites.add(currentCity);
//检查当前结点的所有邻接点
Set<City> cities = currentCity.getRoutes().keySet();
//循环遍历所有邻接点
for (City c :
cities) {
//邻接城市
City city= c;
//当前结点到邻接城市的价格
Integer price = currentCity.getRoutes().get(city);
//如果以当前城市作为中转站所花的价钱更低(因为从起点直达价格可能会更高 or 没有直达的路线,价格为默认值无穷大),更新散列表数据
if ((Integer)routes_from_city.get(city)[0]>price+(Integer) routes_from_city.get(currentCity)[0]){
routes_from_city.put(city,new Object[]{price+(Integer)routes_from_city.get(currentCity)[0],currentCity});
}
}
//决定下一个要访问的城市
currentCity = null;
Integer cheapest = Integer.MAX_VALUE;
//循环遍历散列表,{终点城市:[价格,到达终点前要经过的那个城市]}
//找出剩下的未被访问的终点城市结点中价格最便宜的结点
for (City c :
routes_from_city.keySet()) {
//终点城市
City city = c;
//到达终点城市的价格
Integer price = (Integer) routes_from_city.get(city)[0];
//如果遇到更便宜的城市结点,并且未访问过
if (price<cheapest&&!visited_cites.contains(city)){
cheapest = price;
currentCity = city;
}
}
}
return routes_from_city;
}
}
class Test{
public static void main(String[] args) {
//初始化城市对象
City boston = new City("Boston");
City atlanta = new City("Atlanta");
City elPaso = new City("ElPaso");
City denver = new City("Denver");
City chicago = new City("Chicago");
//添加邻接点
boston.addRoute(chicago,120);
boston.addRoute(denver,180);
chicago.addRoute(elPaso,80);
denver.addRoute(chicago,40);
denver.addRoute(elPaso,140);
elPaso.addRoute(boston,100);
atlanta.addRoute(boston,100);
atlanta.addRoute(denver,160);
//以Atlanta为起点
//Atlanta -> El Paso 最优惠的价格为280元
HashMap<City, Object[]> routes = City.dijkstra(atlanta, new City[]{boston, chicago, denver, elPaso});
for (City c :
routes.keySet()) {
System.out.println("到达"+c.getName()+"最便宜的路线需要"+routes.get(c)[0]+"元");
}
}
}
java实现dijkstra最短路径算法求城市最优惠的买票路线
最新推荐文章于 2024-10-13 23:27:44 发布