这段代码是在做牛客网的编程题的时候写的,但是那道题要求出图中两点之间所有的最短路径,目前我只实现了求出一条最短路径的算法。
Vertex类存储每一个节点的信息:
distance(到源点的距离,初始时设为一个很大的值)
ID(该点的序号)
prior(记录找到最小路径后改点前一个点的ID号)
edge类作为Vertex的一个属性存储该节点所有的出度边及权重。
初始的节点信息保存在ListofVertex 中,算法执行中每求出一个节点到原点的最短路径就把这个节点加入VertexOnLink中,有可能求出的最短路径的节点已经在VertexOnLink中,这种情况会更新VertexOnLink中的信息。
Vertex类:
package testcode;
import java.util.ArrayList;
import java.util.List;
public class Vertex {
public int d,p,ID,current;
public List<Edge>edge = new ArrayList();
public Vertex(int D,int id,int c){
d=D;
p=101;
ID=id;
current=c;
}
public Vertex(int id,int c){
d=10000;
p=101;
ID=id;
current=c;
}
}
Edge类:
package testcode;
public class Edge {
public int head,tail,weight;
public Edge(){
}
public Edge(int h,int t){
this.head=h;
this.tail=t;
}
public Edge(int h,int t,int w){
this.head=h;
this.tail=t;
this.weight=w;
}
}
Main类:
package testcode;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public int capacity,N,indexOfProblem,road;
public ArrayList<Vertex>ListofVertex = new ArrayList();
public ArrayList<Vertex>VertexOnLink = new ArrayList();
public Scanner console;
public Main(){
console = new Scanner(System.in);
}
public void getInfo(){
capacity = console.nextInt();
N = console.nextInt();
indexOfProblem = console.nextInt();
road = console.nextInt();
ListofVertex.add(new Vertex(0,0,10000));
for(int i=1;i < N;i++){
ListofVertex.add(new Vertex(i,console.nextInt()));
}
for(int i=0;i < road;i++){
int[] e={0,0,0};
for(int j=0;j < 3;j++){
e[j]=console.nextInt();
}
ListofVertex.get(e[0]).edge.add(new Edge(e[0],e[1],e[2]));
ListofVertex.get(e[1]).edge.add(new Edge(e[1],e[0],e[2]));
}
}
public void dijkstra(){
VertexOnLink.add(ListofVertex.get(0));
VertexOnLink.get(0).d=0;
while(VertexOnLink.size() < N){
int hid=101,tid=101,minWeight=10000,minDistance=1000000,edge=10000;
for (Vertex v : VertexOnLink) {
for (int j=0;j < v.edge.size();j++){
Edge e = v.edge.get(j);
if((e.weight + v.d <= minDistance) && (v.p != e.tail)){
minDistance=e.weight+v.d;
minWeight=e.weight;
hid=e.head;
tid=e.tail;
edge=j;
}
}
}
ListofVertex.get(hid).edge.remove(edge);
if((minWeight+ListofVertex.get(hid).d) < ListofVertex.get(tid).d){
ListofVertex.get(tid).p=hid;
ListofVertex.get(tid).d=minWeight+ListofVertex.get(hid).d;
VertexOnLink.add(ListofVertex.get(tid));
}
}
for (Vertex v : VertexOnLink) {
System.out.println(v.ID+" "+v.p);
}
}
public void adjust(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Main m = new Main();
m.getInfo();
m.dijkstra();
}
}
测试用例:
运行结果:
根据程序结果画出生成图像: