Advertisement
madegoff

topologic_shortest_path_almost?ready

Jun 24th, 2024 (edited)
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. import java.util.Stack;
  2.  
  3. public class ShortestPathsTopological {
  4. private int[] parent;
  5. private int s;
  6. private double[] dist;
  7.  
  8. public ShortestPathsTopological(WeightedDigraph G, int s) {
  9. // TODO
  10. this.s = s;
  11. this.parent = new int[G.V()];
  12. this.dist = new double[G.V()];
  13.  
  14. for (int i = 0; i < G.V(); i++) {
  15. parent[i] = -1;
  16. dist[i] = Double.POSITIVE_INFINITY;
  17. }
  18. dist[s] = 0;
  19.  
  20. TopologicalWD top_graph = new TopologicalWD(G);
  21. top_graph.dfs(s); //muessen ueberhaupt erstmal ordr finden
  22. Stack<Integer> order = top_graph.order();
  23.  
  24.  
  25. if (!top_graph.hasCycle()){ //azyklisch?
  26. while (!order.isEmpty()){
  27. int v = order.pop();
  28. for (DirectedEdge e : G.incident(v)){
  29. relax(e);
  30. }
  31. }
  32. } //else ??? do nothing???
  33. }
  34.  
  35. public void relax(DirectedEdge e) {
  36. // TODO
  37. int from = e.from();
  38. int to = e.to();
  39. double weight = e.weight();
  40.  
  41. if (dist[from] + weight < dist[to]) { //weg kuerzer gefunden
  42. dist[to] = dist[from] + weight; //aktualisieren
  43. parent[to] = from;
  44. }
  45.  
  46. }
  47.  
  48. public boolean hasPathTo(int v) {
  49. return parent[v] >= 0;
  50. }
  51.  
  52. public Stack<Integer> pathTo(int v) {
  53. if (!hasPathTo(v)) {
  54. return null;
  55. }
  56. Stack<Integer> path = new Stack<>();
  57. for (int w = v; w != s; w = parent[w]) {
  58. path.push(w);
  59. }
  60. path.push(s);
  61. return path;
  62. }
  63. }
  64.  
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement