Advertisement
ramomjcs

Implementação-Grafo

May 21st, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. //MAIN
  2. package proj;
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. public class Main {
  7.  
  8. public static void main(String[] args) {
  9. Graph g = new Graph(5);
  10. g.addEdge(g, 1, 2);
  11. g.addEdge(g, 2, 3);
  12. g.addEdge(g, 3, 4);
  13. g.printGraph(g);
  14. g.DFS(4);
  15. }
  16.  
  17. }
  18.  
  19.  
  20. //graph
  21. package proj;
  22. import java.io.*;
  23. import java.util.*;
  24.  
  25. public class Graph {
  26. public int V;
  27. public LinkedList<Integer> adj[]; //array de lista
  28.  
  29. Graph(int v){ //TAMANHO do grafo(matriz)
  30. this.V = v;
  31. adj = new LinkedList[v]; //cria a lista de adjacencia
  32.  
  33. for (int i=0; i<v; ++i) {
  34. adj[i] = new LinkedList<>(); //cria uma lista encadeada em cada index do array
  35. }
  36. }
  37.  
  38. void addEdge(Graph graph, int v, int w) { //adiciona uma aresta entre os dois vertices v e w
  39. graph.adj[v].add(w);
  40. graph.adj[w].add(v);
  41. }
  42.  
  43. static void printGraph(Graph graph) {
  44. for(int v = 0; v < graph.V; v++) {
  45. System.out.println("Adjacency list of vertex "+ v);
  46. System.out.print("head");
  47. for(Integer pCrawl: graph.adj[v]){
  48. System.out.print(" -> "+pCrawl);
  49. }
  50. System.out.println("\n");
  51. }
  52. }
  53.  
  54. void DFSUtil(int v,boolean visited[])
  55. {
  56. // Mark the current node as visited and print it
  57. visited[v] = true;
  58. System.out.print(v+" ");
  59.  
  60. // Recur for all the vertices adjacent to this vertex
  61. Iterator<Integer> i = adj[v].listIterator();
  62. while (i.hasNext())
  63. {
  64. int n = i.next();
  65. if (!visited[n])
  66. DFSUtil(n, visited);
  67. }
  68. }
  69.  
  70. // The function to do DFS traversal. It uses recursive DFSUtil()
  71. void DFS(int v)
  72. {
  73. // Mark all the vertices as not visited(set as
  74. // false by default in java)
  75. boolean visited[] = new boolean[V];
  76.  
  77. // Call the recursive helper function to print DFS traversal
  78. DFSUtil(v, visited);
  79. }
  80.  
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement