Advertisement
PAXSemperFidelis

Untitled

Nov 30th, 2021
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. import java.util.stream.Stream;
  4. import java.util.LinkedList;
  5. import java.util.Queue;
  6.  
  7. public class Maze
  8. {
  9. public int shortestPath(char[][] maze)
  10. {
  11. int height = maze.length;
  12. int width = maze[0].length;
  13.  
  14. // Implement your path-finding algorithm here!
  15. return 0;
  16. private int V; // No. of vertices
  17. private LinkedList<Integer> adj[]; //Adjacency Lists
  18.  
  19. // Constructor
  20. Graph(int v)
  21. {
  22. V = v;
  23. adj = new LinkedList[v];
  24. for (int i=0; i<v; ++i)
  25. adj[i] = new LinkedList();
  26. }
  27.  
  28. // Function to add an edge into the graph
  29. void addEdge(int v,int w)
  30. {
  31. adj[v].add(w);
  32. }
  33.  
  34. // prints BFS traversal from a given source s
  35. void BFS(int s)
  36. {
  37. // Mark all the vertices as not visited(By default
  38. // set as false)
  39. boolean visited[] = new boolean[V];
  40.  
  41. // Create a queue for BFS
  42. LinkedList<Integer> queue = new LinkedList<Integer>();
  43.  
  44. // Mark the current node as visited and enqueue it
  45. visited[s]=true;
  46. queue.add(s);
  47.  
  48. while (queue.size() != 0)
  49. {
  50. // Dequeue a vertex from queue and print it
  51. s = queue.poll();
  52. System.out.print(s+" ");
  53.  
  54. // Get all adjacent vertices of the dequeued vertex s
  55. // If a adjacent has not been visited, then mark it
  56. // visited and enqueue it
  57. Iterator<Integer> i = adj[s].listIterator();
  58. while (i.hasNext())
  59. {
  60. int n = i.next();
  61. if (!visited[n])
  62. {
  63. visited[n] = true;
  64. queue.add(n);
  65. }
  66. }
  67. }
  68. }
  69.  
  70. // Driver method to
  71. public static void main(String args[])
  72. {
  73. Graph g = new Graph(4);
  74.  
  75. g.addEdge(0, 1);
  76. g.addEdge(0, 2);
  77. g.addEdge(1, 2);
  78. g.addEdge(2, 0);
  79. g.addEdge(2, 3);
  80. g.addEdge(3, 3);
  81.  
  82. System.out.println("Following is Breadth First Traversal "+
  83. "(starting from vertex 2)");
  84.  
  85. g.BFS(2);
  86. }
  87. }
  88. }
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement