Friday, March 11, 2022

Get Connected Components Of A Graph

I/P:

7 5 0 1 10 2 3 10 4 5 10 5 6 10 4 6 10


O/P: [[0, 1], [2, 3], [4, 5, 6]]


package pep.Day38;

import java.io.*;
import java.util.*;


public class Get_Connected_Components_of_Graph {

static class Edge {
int src;
int nbr;
int wt;

Edge(int src, int nbr, int wt) {
this.src = src;
this.nbr = nbr;
this.wt = wt;
}

}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int vtces = Integer.parseInt(br.readLine());
ArrayList<Edge>[] graph = new ArrayList[vtces];
for (int i = 0; i < vtces; i++) {
graph[i] = new ArrayList<>();
}

int edges = Integer.parseInt(br.readLine());
for (int i = 0; i < edges; i++) {
String[] parts = br.readLine().split(" ");
int v1 = Integer.parseInt(parts[0]);
int v2 = Integer.parseInt(parts[1]);
int wt = Integer.parseInt(parts[2]);
graph[v1].add(new Edge(v1, v2, wt));
graph[v2].add(new Edge(v2, v1, wt));
}

ArrayList<ArrayList<Integer>> comps = new ArrayList<>();

// write your code here
boolean[] visited = new boolean[vtces];
ArrayList<Integer> comp = null;
for (int i = 0; i < visited.length; i++) {
System.out.println("for " + i);
System.out.println(comps);
if (!visited[i]) {
comp = new ArrayList<>();
visited[i] = true;
comp.add(i);
dfs(graph, i, visited, comp);
comps.add(comp);
}
}
System.out.println("ans " + comps);
}

public static void dfs(ArrayList<Edge>[] graph, int src, boolean[] visited, ArrayList<Integer> comp) {
for (Edge e : graph[src]) {
System.out.println(e.nbr);
if (!visited[e.nbr]) {
visited[e.nbr] = true;
comp.add(e.nbr);
dfs(graph, e.nbr, visited, comp);
}
}
}
}

Time Complexity:

The time complexity of the above code is O(V) as we are going to visit every vertex exactly once.

Space Complexity:

The space complexity of the above code is O(h) where h is the height of the recursion stack.

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...