Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import java.util.*;
  2. public class COSC336Assignment7 {
  3.  
  4. public static void main(String[] args) {
  5. // TODO Auto-generated method stub
  6. ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
  7. // number of vertices
  8. int v = 7;
  9. // construction of the graph
  10. graph.get(0).add(1);
  11. graph.get(0).add(2);
  12. graph.get(0).add(3);
  13. graph.get(0).add(4);
  14. graph.get(0).add(5);
  15. graph.get(1).add(6);
  16. graph.get(2).add(6);
  17. graph.get(3).add(6);
  18. graph.get(4).add(6);
  19. graph.get(5).add(6);
  20. int starting = 0; //starting node
  21. int destination = 6; //ending node
  22. System.out.print("All paths from starting node ");
  23. System.out.print(starting);
  24. System.out.print(" to destination ");
  25. System.out.print(destination);
  26. System.out.print(" are:");
  27. System.out.println();
  28. // function for finding the paths
  29. getPaths(graph, starting, destination, v);
  30. System.out.print("\nShortest paths can be seen from the lengths.\n");
  31.  
  32.  
  33. }
  34. public static void getPaths(ArrayList<ArrayList<Integer>> g, int starting, int destination, int v) {
  35. Queue<ArrayList<Integer>> q = null;
  36. int length;
  37. ArrayList<Integer> path = null;
  38. path.add(starting);
  39. q.add(path);
  40. while(!q.isEmpty()) {
  41. path = q.peek();
  42. q.remove();
  43. int last = path.get(path.size()-1);
  44. length = path.size();
  45. if(last == destination) {
  46. System.out.println("Length of path " + length);
  47. displayPath(path);
  48. }
  49. for(int i = 0; i < g.get(last).size(); i++) {
  50. if(notVisited(g.get(last).get(i), path) != 0) {
  51. ArrayList<Integer> nPath = path;
  52. nPath.add(g.get(last).get(i));
  53. q.add(nPath);
  54. }
  55. }
  56. }
  57. }
  58. public static void displayPath(ArrayList<Integer> path) {
  59. int size = path.size();
  60. for(int i = 0; i < size; i++)
  61. System.out.println(path.get(i) + " ");
  62. }
  63. public static int notVisited(int x, ArrayList<Integer> path) {
  64. int size = path.size();
  65. for(int i = 0; i < size; i++) {
  66. if(path.get(i) == x)
  67. return 0;
  68. }
  69. return 1;
  70. }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement