Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Solution {
  4. /**
  5. * Find the shortest path between v and u in the graph g.
  6. *
  7. * @param g
  8. * graph to search in.
  9. * @param v
  10. * node to start from.
  11. * @param u
  12. * node to reach.
  13. * @return the nodes you that form the shortest path, including v and u. An
  14. * empty list iff there is no path between v and u.
  15. */
  16. public static List<Vertex> shortestPath(Graph g, Vertex v, Vertex u) {
  17. List<Vertex> slowPath = new ArrayList<>();
  18. Iterator<Vertex> it = new GraphIterator(g,v);
  19.  
  20. while (it.hasNext())
  21. {
  22. Vertex x = it.next();
  23.  
  24. slowPath.add(x);
  25.  
  26. if (x == u)
  27. {
  28. break;
  29. }
  30. }
  31.  
  32. if (slowPath.get(slowPath.size() - 1) != u)
  33. {
  34. // Not found
  35. return new ArrayList<>();
  36. }
  37.  
  38. List<Vertex> fastButReversedPath = new ArrayList<>();
  39. int i = slowPath.size() - 1;
  40.  
  41. while (true)
  42. {
  43. Vertex c = slowPath.get(i);
  44. List<Vertex> connected = g.getNeighbours(c);
  45.  
  46. fastButReversedPath.add(c);
  47.  
  48. if (c == v)
  49. {
  50. Collections.reverse(fastButReversedPath);
  51.  
  52. return fastButReversedPath;
  53. }
  54.  
  55. for (Vertex vertex : connected)
  56. {
  57. if (fastButReversedPath.contains(vertex))
  58. {
  59. continue;
  60. }
  61.  
  62. for (int j = 0; j < i; j++)
  63. {
  64. if (slowPath.get(j) == vertex)
  65. {
  66. i = j;
  67. }
  68. }
  69. }
  70. }
  71. }
  72. }
  73. //
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement