-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCW_4.java
More file actions
72 lines (57 loc) · 1.73 KB
/
Copy pathCW_4.java
File metadata and controls
72 lines (57 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
public class CW_4 {
static int V; // Total vertices
static LinkedList<Integer>[] adjList; //Adjacency list
static ArrayList<ArrayList<Integer>> components = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input
String s = scanner.nextLine();
int numberEdges = scanner.nextInt();
V = (s.length() - 1) / 2;
adjList = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjList[i] = new LinkedList();
}
for (int i = 0; i < numberEdges; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
addEdge(u, v);
}
// Logic performing DFS
DFS();
// Output
System.out.println(numberOfConnectedComponents());
}
// Adding edge into graph
public static void addEdge(int u, int v)
{
adjList[u].add(v);
adjList[v].add(u);
}
static int numberOfConnectedComponents() {
return components.size();
}
static void DFS()
{
boolean[] isVisited = new boolean[V];
for (int i = 0; i < V; i++) {
ArrayList<Integer> list = new ArrayList<>();
if (!isVisited[i]) {
DFSUtil(i, isVisited, list);
components.add(list);
}
}
}
static void DFSUtil(int v, boolean[] isVisited, ArrayList<Integer> list) {
isVisited[v] = true;
list.add(v);
System.out.print(v + " ");
for (int n : adjList[v]) {
if (!isVisited[n])
DFSUtil(n, isVisited, list);
}
}
}