Advertisement
amitsen01ei

ConnectedComponents.java

Oct 16th, 2023 (edited)
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | Source Code | 0 0
  1. public class ConnectedComponents {
  2.  
  3.     /**
  4.      * Returns the number of connected components in the graph.
  5.      *
  6.      * Time complexity: O(A + B) where A is the number of nodes and B is the number of edges.
  7.      * Space complexity: O(A + B) for storing the graph and visited set.
  8.      *
  9.      * @param A Number of nodes in the graph.
  10.      * @param B 2D array representing the edges of the graph.
  11.      * @return Number of connected components.
  12.      */
  13.     public int solve(int A, int[][] B) {
  14.         Map<Integer, List<Integer>> graph = new HashMap<>();
  15.         for (int i = 1; i <= A; i++) {
  16.             graph.put(i, new ArrayList<>());
  17.         }
  18.         for (int[] edge : B) {
  19.             graph.get(edge[0]).add(edge[1]);
  20.             graph.get(edge[1]).add(edge[0]);
  21.         }
  22.        
  23.         // Set to keep track of visited nodes.
  24.         Set<Integer> visited = new HashSet<>();
  25.  
  26.         int components = 0;
  27.         for (int i = 1; i <= A; i++) {
  28.             if (!visited.contains(i)) {
  29.                 dfs(i, graph, visited);
  30.                 components++;
  31.             }
  32.         }
  33.         return components;
  34.     }
  35.  
  36.     private static void dfs(int node, Map<Integer, List<Integer>> graph, Set<Integer> visited) {
  37.         if (visited.contains(node)) return;
  38.         visited.add(node);
  39.         for (int neighbor : graph.get(node)) {
  40.             dfs(neighbor, graph, visited);
  41.         }
  42.     }
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement