巡回セールスマン問題
このプログラミングを実際に視覚的(探索している状況など)に表したいんですが、どのようにすべきなのでしょうか?
いろいろ参考書を見たのですが、わかりませんでした。
import java.io.*;
public class TSP {
public static void main(String[] args) {
TSP instance = new TSP();
TspPoint[] points = new TspPoint[5];
//コンポーネントの作成
points[0] = new TspPoint("A", 5, 10);
points[1] = new TspPoint("B", 4, 2);
points[2] = new TspPoint("C", 6, 3);
points[3] = new TspPoint("D", 3, 4);
points[4] = new TspPoint("E", 2, 7);
instance.setPoints(points);
instance.traveling();
instance.dispResult();
}
private TspPoint[] points;
private double min_distance;
private int[] min_route;
public void setPoints(TspPoint[] points) {
this.points = points;
}
public void traveling() {
min_distance = Double.MAX_VALUE;
min_route = new int[points.length];
int p1, p2, p3, p4, p5;
p1 = 0;
for (p2 = 1; p2 < 5; p2++) {
for (p3 = 1; p3 < 5; p3++) {
for (p4 = 1; p4 < 5; p4++) {
for (p5 = 1; p5 < 5; p5++) {
if (p1 == p2 || p1 == p3 || p1 == p4 || p1 == p5
|| p2 == p3 || p2 == p4 || p2 == p5 || p3 == p4
|| p3 == p5 || p4 == p5) {
// 重複する地点は対象外
} else {
// p1→p2→p3→p4→p5→p1への巡回経路長を求める
double distance = 0.0;
distance += calcDistance(points[p1], points[p2]);
distance += calcDistance(points[p2], points[p3]);
distance += calcDistance(points[p3], points[p4]);
distance += calcDistance(points[p4], points[p5]);
distance += calcDistance(points[p5], points[p1]);
if (distance < min_distance) {
// 現在のところの最短経路を覚えておく
min_route[0] = p1;
min_route[1] = p2;
min_route[2] = p3;
min_route[3] = p4;
min_route[4] = p5;
// 最短距離を記憶する
min_distance = distance;
}
}
}
}
}
}
}
public void dispResult() {
System.out.print("最小の巡回経路は ");
for (int i = 0; i < 5; i++) {
System.out.print(points[min_route[i]].toString() + " → ");
}
System.out.println(points[min_route[0]].toString());
System.out.println("巡回経路長は " + min_distance);
}
public double calcDistance(TspPoint a, TspPoint b) {
double temp;
temp = (a.getX() - b.getX()) * (a.getX() - b.getX())
+ (a.getY() - b.getY()) * (a.getY() - b.getY());
return Math.sqrt(temp); //平方根を返す
}
}
class TspPoint {
private String name;
private int x;
private int y;
public TspPoint(String name, int x, int y) {
this.name = name;
this.x = x;
this.y = y;
}
public String getName() {
return name;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public String toString() {
return name + "(" + x + "," + y + ")";
}
}