首先是图的定义类
package graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 定义简单图,为最短路径算法准备
* @author root
*
*/
public class SimplGraph {
/**
* 节点值
*/
public int key;
/**
* 相邻节点集合
*/
public List<Integer> nearNode;
/**
* 两节点之间的权重(距离)
*/
public Map<String,Integer> weight;
/**
* 初始化参数
* @param key
*/
public SimplGraph(int key){
this.key = key;
nearNode = new ArrayList<Integer>();
weight = new HashMap<String,Integer>();
}
/**
* 添加邻节点
* 张磊
*2007-6-23
*@param node
*@param lengh
*/
public void addNode(int node,int lengh){
//加入邻节点中
nearNode.add(node);
//记录类节点和node 节点的权重
weight.put(Integer.toString(node), lengh);
}
}
接下来是最短路径基本算法的实现类
package graph;
import java.util.Iterator;
/**
* 最短路径算法
* @author root
*
*/
public class Dijkstra {
SimplGraph[] total;
/**
* 初始化数据
*
*/
public Dijkstra(){
total = new SimplGraph[6];
//设置一个图
int a = 0,b = 1,c = 2,d = 3,e = 4,f = 5 ;
SimplGraph Sa = new SimplGraph(0);
SimplGraph Sb = new SimplGraph(9999);
SimplGraph Sc = new SimplGraph(9999);
SimplGraph Sd = new SimplGraph(9999);
SimplGraph Se = new SimplGraph(9999);
SimplGraph Sf = new SimplGraph(9999);
//设置每个节点的邻节点及权值
Sa.addNode(b,1);
Sa.addNode(c,4);
Sa.addNode(d,7);
Sb.addNode(a,1);
Sb.addNode(c,1);
Sb.addNode(e,3);
Sc.addNode(a,4);
Sc.addNode(b,1);
Sc.addNode(d,3);
Sc.addNode(f,6);
Sd.addNode(a,7);
Sd.addNode(c,3);
Sd.addNode(f,9);
Se.addNode(b,3);
Se.addNode(f,5);
Sf.addNode(c,6);
Sf.addNode(d,9);
Sf.addNode(e,5);
//设置每个节点的索引
total[a] = Sa;
total[b] = Sb;
total[c] = Sc;
total[d] = Sd;
total[e] = Se;
total[f] = Sf;
}
/**
* 最短路径计算(基本算法)
* 张磊
*2007-6-22
*/
public void minPath(){
for (int i = 0; i < total.length; i++) {
Iterator it = total[i].nearNode.iterator();
while(it.hasNext()){
//得到节点的数字索引
int node = (Integer)it.next();
//通过索引得到节点的类
SimplGraph sg = total[node];
//对此节点进行最短路径计算
if(sg.key>total[i].key+total[i].weight.get(Integer.toString(node)))
sg.key = total[i].key+total[i].weight.get(Integer.toString(node));
}
}
}
public static void main(String[] args){
Dijkstra d = new Dijkstra();
d.minPath();
SimplGraph[] s = d.total;
for (int i = 0; i < s.length; i++) {
System.out.println("节点 "+i);
System.out.println("最短路径为 "+s[i].key);
}
}
}