Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- public class ShortestPathsTopological {
- private int[] parent;
- private int s;
- private double[] dist;
- public ShortestPathsTopological(WeightedDigraph G, int s) {
- // TODO
- this.s = s;
- this.parent = new int[G.V()];
- this.dist = new double[G.V()];
- for (int i = 0; i < G.V(); i++) {
- parent[i] = -1;
- dist[i] = Double.POSITIVE_INFINITY;
- }
- dist[s] = 0;
- TopologicalWD top_graph = new TopologicalWD(G);
- top_graph.dfs(s); //muessen ueberhaupt erstmal ordr finden
- Stack<Integer> order = top_graph.order();
- if (!top_graph.hasCycle()){ //azyklisch?
- while (!order.isEmpty()){
- int v = order.pop();
- for (DirectedEdge e : G.incident(v)){
- relax(e);
- }
- }
- } //else ??? do nothing???
- }
- public void relax(DirectedEdge e) {
- // TODO
- int from = e.from();
- int to = e.to();
- double weight = e.weight();
- if (dist[from] + weight < dist[to]) { //weg kuerzer gefunden
- dist[to] = dist[from] + weight; //aktualisieren
- parent[to] = from;
- }
- }
- public boolean hasPathTo(int v) {
- return parent[v] >= 0;
- }
- public Stack<Integer> pathTo(int v) {
- if (!hasPathTo(v)) {
- return null;
- }
- Stack<Integer> path = new Stack<>();
- for (int w = v; w != s; w = parent[w]) {
- path.push(w);
- }
- path.push(s);
- return path;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement