A*搜索算法
实例:城市最短路径代码实现
public class InformedSearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] cities = {
"1号","2号","3号","4号","5号","6号","7号","8号"
};
// 数组模拟图,数组下标为城市对应下标,如distance[0][1]对应cities[0],cities[1],数组值为城市间直线距离
int[][] distance = {
{0,3,7,9,1,4,3,8},
{3,0,5,7,4,6,5,7},
{7,5,0,4,7,10,8,9},
{9,7,4,0,5,7,9,9},
{1,4,7,5,0,4,1,7},
{4,6,10,7,4,0,2,4},
{3,5,8,9,1,4,0,6},
{8,7,9,9,7,4,6,0}
};
// 表示城市间是否相连
boolean[][] isconnect = {
{true,true,false,false,true,false,false,false},
{true,true,true,true,false,false,false,false},
{false,true,true,false,false,false,false,true},
{false,true,false,true,false,false,false,true},
{true,false,false,false,true,true,true,false},
{false,false,false,false,true,true,false,true},
{false,false,false,false,true,false,true,true},
{false,false,true,true,false,true,true,true}
};
FindRoad find = new FindRoad("4号","5号"); // 起始城市,目标城市
find.setroad(cities, distance, isconnect);
find.print();
}
}
class FindRoad{
private String startcity;
private String endcity; // 目标城市
private City root; // 链表模拟路径
private int endnum; // 目标城市下标
private int sumlong = 0;
// 构造器
public FindRoad(String startcity,String endcity)
{
this.startcity = startcity;
this.endcity = endcity;
}
// 打印
public void print()
{
City temp = root;
while(temp!=null)
{
temp.print();
temp = temp.next;
}
System.out.println("总里程 ="+sumlong+"km");
}
// 设置路径
public void setroad(String[] cities,int[][] distance,boolean[][] isconnect)
{
root = new City(startcity); // 建立头节点
this.endnum = findend(cities); // 找到目标城市对应下标
if(endnum == -1) // 若为 -1 则为找到相应城市
{
return;
}
City temp = root; // 临时节点
while(true)
{
int n = findcity(cities,distance,isconnect); // 找到下一个要到达城市下标
City t = new City(cities[n]); // 创建城市节点
temp.next = t; // 连接节点
temp = t; // 移动临时节点
this.startcity = cities[n]; // 改变下一个节点为新的起始节点
if(cities[n].equals(this.endcity)) // 是否到达目标城市
{
break;
}
}
}
// 查找目标城市下标
private int findend(String[] cities)
{
for(int i=0;i");
}
}