Skip to content

Commit 6811d3b

Browse files
Create Graphs:All connected components
1 parent cb3ec57 commit 6811d3b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Graphs:All connected components

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.LinkedList;
2+
import java.util.Scanner;
3+
import java.util.Queue;
4+
// import java.io.*;
5+
import java.util.*;
6+
public class Solution{
7+
public static void help(int edges[][],boolean visited[],ArrayList<Integer> arr,int start){
8+
visited[start]=true;
9+
arr.add(start);
10+
int n=edges.length;
11+
for(int j=0;j<n;j++){
12+
if(edges[start][j]==1&&!visited[j]){
13+
help(edges,visited,arr,j);
14+
}
15+
}
16+
}
17+
public static void helpp(int edges[][]){
18+
boolean visited[]=new boolean[edges.length];
19+
for(int i=0;i<edges.length;i++){
20+
if(!visited[i]){
21+
// this array list is creating again and again
22+
ArrayList<Integer> arrans= new ArrayList<Integer>();
23+
help(edges,visited,arrans,i);
24+
Collections.sort(arrans);
25+
for(int j=0;j<arrans.size();j++)
26+
System.out.print(arrans.get(j)+" ");
27+
System.out.println();
28+
}
29+
}
30+
}
31+
public static void main(String[] args){
32+
Scanner s = new Scanner(System.in);
33+
int n = s.nextInt();
34+
// total number of edges e
35+
int e = s.nextInt();
36+
int edges[][]=new int[n][n];
37+
for(int i=0;i<e;i++){
38+
int fv=s.nextInt();
39+
int sv=s.nextInt();
40+
edges[fv][sv]=1;
41+
edges[sv][fv]=1;
42+
}
43+
helpp(edges);
44+
}
45+
}

0 commit comments

Comments
 (0)