The shortest path problem is to give a graph. The edges in this graph are backward and weighted. Calculate the shortest path from s to t.
There are many types of Shortest Path Problems. It can be divided:
From one vertex to another
From one vertex to all other vertices
From all vertices to all vertices
Edge weight can be divided:
Non-negative weight
Arbitrary permission
Euclidean privilege
It can be divided
No-ring Shortest Path
Shortest Path without negative Loops
Class Definition
Before implementing the shortest path algorithm, you must define a directed weight graph in the program.
The directed weight edge is defined as follows:
public class DirectedEdge { private int v; private int w; private double weight; public DirectedEdge(int v, int w, double weight) { this.v = v; this.w = w; this.weight = weight; } public int from() { return v; } public int to() { return w; } public double weight() { return this.weight; } @Override public String toString() { return String.format("%s->%s[%s]", v, w, weight); }}
A directed weight chart is defined as follows:
import java.util.LinkedList; public class EdgeWeightedDigraph { private int V; private LinkedList
[] adj; public EdgeWeightedDigraph(int V) { this.V = V; adj = new LinkedList[V]; for (int i = 0; i < V; i++) { adj[i] = new LinkedList
(); } } public void addEdge(DirectedEdge edge) { int v = edge.from(); adj[v].add(edge); } public Iterable
adj(int v) { return adj[v]; } public int V() { return V; } public int E() { int result = 0; for (LinkedList
e : adj) { result += e.size(); } return result; } @Override public String toString() { String result = ""; for (int i = 0; i < adj.length; i++) { result += i + ":"; for (DirectedEdge e : adj[i]) { result += String.format(" %s[%s]", e.to(), e.weight()); } } return result; }}
The advantage of defining a directed weight graph is that there can be a self-join to achieve multiple connections between vertices.
The shortest path algorithm interface is as follows:
public class SP { public double distTo(int v); public Iterable
pathTo(int v);}