做金山WPS笔试的时候遇到了一些最短路径的变形题,于是自己重新复习一遍Dijkstra算法。这也是我第一次主动自己写算法详解。首先要先定义好图中的每个边。
// 代表着从v-w的一条边 public class DirectedEdge { private int v;private int w;private double weight;//v 代表着一条边的出度点,w代表着一条边的入度点;weight表示这条边的权重
public DirectedEdge(int v,int w,double weight) { this.v=v; this.w=w; this.weight=weight; } double Weight() { return weight; } int from() { return v; } int to() { return w; } }
//之后再定义好一个图;这里使用了栈数组来保存图中所有的边
public class EdgeWeightedDigrah { int v; int e; private Stack<DirectedEdge>[] adj; //adj[v]代表着从顶点v出度的所有边 public EdgeWeightedDigrah(int v) { this.v=v; this.e=0; adj=(Stack<DirectedEdge>[])new Stack[v]; for(int i=0;i<v;i++) adj[i]=new Stack<>(); } int v() { return v; } int E() { return e; } public void addEdge(DirectedEdge edge) { adj[edge.from()].add(edge); e++; } public Iterable<DirectedEdge> adj(int v) { return adj[v]; } public Iterable<DirectedEdge> edges() { Stack<DirectedEdge> stack=new Stack<>(); for(int i=0;i<v;i++) { for(DirectedEdge edge:adj[v]) { stack.add(edge); } } return stack; } }
以下就以这个图为例讲解Dijkstra算法
再就是Dijkstra算法的代码了
public class Dijkstra { private DirectedEdge[] edgeTo; private double[] distTo; private IndexMinPQ<Double> pq; //一个带索引的有限队列 其实就是一个带索引的最小堆 distTo=new double[G.v()]; pq=new IndexMinPQ<Double>(G.v()); for(int v=0;v<G.v();v++) { distTo[v]=Double.POSITIVE_INFINITY; distTo[s]=0.0; pq.insert(s,0.0); while(!pq.isEmpty()) { relax(G,pq.delMin()); } } }
// relax代表着松弛表中的meiyitiaobian public void relax(EdgeWeightedDigrah G,int v) { for(DirectedEdge e:G.adj(v)) { int w=e.to(); if(distTo[w]>distTo[v]+e.Weight()) { distTo[w]=distTo[v]+e.Weight(); edgeTo[w]=e; if(pq.contains(w)) pq.changeKey(w,distTo[w]); else pq.insert(w,distTo[w]); } } } public double distTo(int v) { return distTo[v]; } public boolean hashpathTo(int v) { return distTo[v]<Double.POSITIVE_INFINITY; } public Iterable<DirectedEdge> pathTo(int v) { if(!hashpathTo(v)) return null; Stack<DirectedEdge> path=new Stack<DirectedEdge>(); for(DirectedEdge e=edgeTo[v];e!=null;e=edgeTo[e.from()]) path.push(e); return path; } }