日期:2014-05-20 浏览次数:20809 次
package tm.cao.tu;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//专门用于迪杰斯特拉算法的类
public class Dijkstra{
//顶点集合
private List<DingDian> dianList;
//关系集合
private List<GuanXi> guanxiList;
public List<DingDian> getDianList() {
return dianList;
}
public List<GuanXi> getGuanxiList() {
return guanxiList;
}
public void setDianList(List<DingDian> dianList) {
this.dianList = dianList;
}
public void setGuanxiList(List<GuanXi> guanxiList) {
this.guanxiList = guanxiList;
}
//构造器
public Dijkstra(List<DingDian> dianList, List<GuanXi> guanxiList, Integer flag) {
super();
this.dianList = dianList;
//有向图
if(flag==0){
this.guanxiList=guanxiList;
}else if(flag==1){
//如果是无向图,则需要加入反序的关系
List<GuanXi> list2=new ArrayList<GuanXi>();
for(GuanXi gx:guanxiList){
GuanXi fan=new GuanXi(gx.getWei(), gx.getTou(), gx.getQuan());
list2.add(fan);
}
guanxiList.addAll(list2);
this.guanxiList=guanxiList;
}else{
//无论如何也不扩展边集 相当于只创建边集数组
this.guanxiList=guanxiList;
}
}
//构造邻接表
public void createLingJieBiao(){
if(guanxiList.size()>0){
Collections.sort(guanxiList);
}
for(GuanXi gx:guanxiList){
DingDian tou=gx.getTou();
Hu q=new Hu(gx.getWei(), gx.getQuan());
q.setId(gx.getId());
//入度+1 对应于拓扑排序
DingDian wei=gx.getWei();
int rudu=wei.getRudu();
rudu++;
wei.setRudu(rudu);
if(tou.getFirstHu()==null){
tou.setFirstHu(q);
}else{
Hu p=tou.getFirstHu();
while(p.getNextHu()!=null){
p=p.getNextHu();
}
p.setNextHu(q);
}
}
}
/**迪杰斯克拉算法 http://baike.baidu.com/view/1939816.htm
*sList:需要求的顶点集合 一开始只有一个点 dist属性:记录长度,path属性:记录路径的数组
*/
public List<DingDian> disjaktra(DingDian which){
this.createLingJieBiao();
List<DingDian> sList=new ArrayList<DingDian>();
//为了计算dist方便 设置一个动态集合 用于记录dist已经不是null的点
List<DingDian> dongtaiList=new ArrayList<DingDian>();