爬山算法(Hill Climbing)解决旅行商问题(TSP)

何为TSP问题?

旅行商问题 TSP(Travelling Salesman Problem)是数学领域中著名问题之一。

  • 场景:一个旅行商人需要拜访n个城市
  • 条件:要选择一个路径能够拜访到所有的城市,且每个城市只能被拜访一次,最终回到起点
  • 目标:求得的路径路程为所有路径可能之中的最小值

TSP问题被证明是NP完全问题,这类问题不能用精确算法实现,而需要使用相似算法。

TSP问题分为两类:对称TSP(Symmetric TSP)以及非对称TSP(Asymmetric TSP)

对称与非对称TSP区别

本文解决的是对称TSP
假设:A表示城市A,B表示城市B,D(A->B)为城市A到城市B的距离,同理D(B->A)为城市B到城市A的距离
对称TSP中,D(A->B) = D(B->A),城市间形成无向图
非对称TSP中,D(A->B) ≠ D(B->A),城市间形成有向图

什么情况下会出现非对称TSP呢?

现实生活中,可能出现单行线、交通事故、机票往返价格不同等情况,均可以打破对称性。

何为爬山算法(Hill Climbing)?

爬山算法是一种局部择优的方法,采用启发式方法。直观的解释如下图:

爬山算法(Hill Climbing)解决旅行商问题(TSP)_第1张图片
一系列山峰与峡谷的剖面图

爬山算法,顾名思义就是爬山,找到第一个山峰的时候就停止,作为算法的输出结果。所以,爬山算法容易把局部最优解A作为算法的输出,而我们的目的是找到全局最优解B。

如何让算法有更大的可能性搜索到全局最优解B呢?

如下图所示,尽管在这个图中的许多局部极大值,仍然可以使用模拟退火算法(Simulated Annealing)发现全局最大值。

图片来源:wikipedia

对于模拟退火的内容在此不予赘述,有机会另写一文详述,如感兴趣请访问 大白话解析模拟退火算法

Java实现爬山算法解决旅行商问题

必要解释详见注释

/**
 * 城市实体类
 * 实现计算城市间距离方法
 * @author Frank CHEN
 *
 */
public class City {
    // 地球赤道半径
    private static final double ERATH_EQUATORIAL_RADIUS = 6378.1370D;
    
    private static final double CONCVERT_DEGREES_TO_RADIANS = Math.PI / 180;
    // 经度
    private double longitude;
    // 纬度
    private double latitude;
    // 城市名
    private String name;
    
    public City(double longitude, double latitude, String name) {
        super();
        this.longitude = longitude;
        this.latitude = latitude;
        this.name = name;
    }
    
    public double getLongitude() {
        return longitude;
    }
    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }
    public double getLatitude() {
        return latitude;
    }
    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return this.name;
    }
    
    /**
     * 计算传入城市与当前城市的实际距离
     * @param city
     * @return
     */
    public double measureDistance(City city) {
        double deltaLongitude = deg2rad(city.getLongitude() - this.getLongitude());
        double deltaLatitude = deg2rad(city.getLatitude() - this.getLatitude());
        double a = Math.pow(Math.sin(deltaLatitude / 2D), 2D) 
                + Math.cos(deg2rad(this.getLatitude())) 
                * Math.cos(deg2rad(city.getLatitude())) 
                * Math.pow(Math.sin(deltaLongitude / 2D), 2D);
        return  ERATH_EQUATORIAL_RADIUS * 2D * Math.atan2(Math.sqrt(a), Math.sqrt(1D - a));
    }
    
    // 转化为弧度
    private double deg2rad(double deg) {
          return deg * CONCVERT_DEGREES_TO_RADIANS;
    }
}

此处根据经纬度计算城市间距离的公式,请参考Calculate distance between two latitude-longitude points? (Haversine formula)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/**
 * 路径实体类
 * @author Frank CHEN
 *
 */
public class Route {
    private ArrayList cities = new ArrayList<>();
    
    /**
     * 构造方法
     * 随机打乱cities排序
     * @param cities
     */
    public Route(ArrayList cities) {
        this.cities.addAll(cities);
        Collections.shuffle(this.cities);
    }
    
    public Route(Route route) {
        for(City city : route.getCities()) {
            this.cities.add(city);
        }
    }
    
    /**
     * 计算城市间总距离
     * @return
     */
    public double getTotalDistance() {
        int citiesSize = this.cities.size();
        double sum = 0D;
        int index = 0;
        while(index < citiesSize - 1) {
            sum += this.cities.get(index).measureDistance(this.cities.get(index + 1));
            index++;
        }
        sum += this.cities.get(citiesSize - 1).measureDistance(this.cities.get(0));
        return sum;
    }
    
    public String getTotalStringDistance() {
        String returnString = String.format("%.2f", this.getTotalDistance());
        return returnString;
    }
    
    public ArrayList getCities() {
        return cities;
    }
    
    public void setCities(ArrayList cities) {
        this.cities = cities;
    }

    @Override
    public String toString() {
        return Arrays.toString(cities.toArray());
    }
    
} 


/**
 * 实现爬山算法
 * @author Frank CHEN
 *
 */
public class HillClimbing {
    // 最大迭代次数
    public static final int ITERATIONS_BEFORE_MAXIMUM = 1500;
    
    /**
     * 寻找最短路径
     * @param currentRoute
     * @return
     */
    public Route findShortestRoute(Route currentRoute) {
        Route adjacentRoute;
        int iterToMaximumCounter = 0;
        String compareRoutes = null;
        while(iterToMaximumCounter < ITERATIONS_BEFORE_MAXIMUM) {
            adjacentRoute = obtainAdjacentRoute(new Route(currentRoute));
            if(adjacentRoute.getTotalDistance() <= currentRoute.getTotalDistance()) {
                compareRoutes = "<= (更新)";
                iterToMaximumCounter = 0;
                currentRoute = new Route(adjacentRoute);
            } else {
                compareRoutes = "> (保持) - 迭代次数 # " + iterToMaximumCounter;
                iterToMaximumCounter++;
            }
            System.out.println("       | " + compareRoutes);
            System.out.print(currentRoute + " |      " + currentRoute.getTotalStringDistance());
        }
        
        System.out.println("       | 可能的最优解");
        
        return currentRoute;
    }
    
    /**
     * 随机交换两个城市位置
     * @param route
     * @return
     */
    public Route obtainAdjacentRoute(Route route) {
        int x1 = 0, x2 = 0;
        while(x1 == x2) {
            x1 = (int) (route.getCities().size() * Math.random());
            x2 = (int) (route.getCities().size() * Math.random());
        }
        
        City city1 = route.getCities().get(x1);
        City city2 = route.getCities().get(x2);
        
        // swap two stochastic cities
        route.getCities().set(x2, city1);
        route.getCities().set(x1, city2);
        return route;
    }
}

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 初始化城市数据
 * main方法
 * @author Frank CHEN
 *
 */
public class Driver {
    private ArrayList initialCities = new ArrayList(Arrays.asList(
            new City(116.41667, 39.91667, "北京"),
            new City(121.43333, 34.50000, "上海"),
            new City(113.00000, 28.21667, "长沙"),
            new City(106.26667, 38.46667, "银川"),
            new City(109.50000, 18.20000, "三亚"),
            new City(112.53333, 37.86667, "太原"),
            new City(91.00000, 29.60000, "拉萨"),
            new City(102.73333,  25.05000, "昆明"),
            new City(126.63333, 45.75000, "哈尔滨"),
            new City(113.65000, 34.76667, "郑州"),
            new City(113.50000, 22.20000, "澳门")));
    
    public static void main(String[] args) {
        Driver driver = new Driver();
        Route route = new Route(driver.initialCities);
        new HillClimbing().findShortestRoute(route);
    }
}

此处初始化数据源可以使用TSPLIB中所提供的数据,此程序大致阐述爬山算法的实现。

爬山算法(Hill Climbing)解决旅行商问题(TSP)_第2张图片
运行result

编写于一个失眠夜


菜鸟一枚,欢迎评论区相互交流,加速你我成长•ᴗ•。

你可能感兴趣的:(爬山算法(Hill Climbing)解决旅行商问题(TSP))