File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java.util.Scanner;
2
+ import java.util.Queue;
3
+ import java.util.*;
4
+
5
+ public class Solution {
6
+
7
+ public static void printHelper(int edges[][], int sv,boolean visited[]){
8
+ Queue<Integer> q = new LinkedList<>();
9
+ q.add(sv);
10
+ visited[sv]=true;
11
+ while(q.size()!=0){
12
+ int firstelem = q.remove();
13
+ System.out.print(firstelem+" ");
14
+ for(int i=0; i<edges.length; i++){
15
+ if(edges[firstelem][i]==1 && !visited[i]){
16
+ q.add(i);
17
+ visited[i]=true;
18
+ }
19
+ }
20
+ }
21
+ }
22
+ // we have to deal with both connected and non connected
23
+ public static void print(int edges[][]){
24
+ boolean visited[] = new boolean[edges.length];
25
+ for(int i=0; i< edges.length; i++){
26
+ if(!visited[i]){
27
+ printHelper(edges, i, visited);
28
+ }
29
+ }
30
+ }
31
+ public static void main(String[] args) {
32
+ Scanner s = new Scanner(System.in);
33
+ int V = s.nextInt();
34
+ int E = s.nextInt();
35
+ int edges[][] = new int[V][V];
36
+ for(int i =0; i< E; i++){
37
+ int fv = s.nextInt();
38
+ int sv = s.nextInt();
39
+ edges[fv][sv] = 1;
40
+ edges[sv][fv] =1;
41
+ }
42
+ print(edges);
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments