Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. class Solution {
  2.   /**
  3.    * Counts the number of vertices in the same connected component as v in graph g.
  4.    * This is done using depth first search.
  5.    *
  6.    * Returns 0 if the graph or vertex is null
  7.    *
  8.    * @param g
  9.    *     The graph to count vertices in.
  10.    * @param v
  11.    *     The vertex to start counting at.
  12.    * @return the number of vertices in the same connected component.
  13.    */
  14.   public static int countVertices(Graph g, Graph.Vertex v) {
  15.     if(g == null || v == null) return 0;
  16.    
  17.     Set<Graph.Vertex> visited = new HashSet<>();
  18.     Stack<Graph.Vertex> stack = new Stack<>();
  19.     int vertices = 0;
  20.     Graph.Vertex vertex = v;
  21.     stack.push(vertex);
  22.    
  23.     while(!stack.empty()){
  24.       visited.add(vertex);
  25.       List<Graph.Vertex> neighbours = g.getNeighbours(vertex);
  26.       for(Graph.Vertex vrtx : neighbours){
  27.         if(!visited.contains(vrtx)){
  28.           stack.push(vrtx);
  29.         }
  30.       }
  31.       vertex = stack.pop();
  32.       vertices++;
  33.     }
  34.     return vertices;
  35.   }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement