-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA1_ConnectedComponenets.java
87 lines (75 loc) · 1.96 KB
/
A1_ConnectedComponenets.java
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// There are N cities, and M routes[], each route is a path between two cities.
// routes[i] = [city1, city2], there is a travel route between city1 and city2.
// Each city is numbered from 0 to N-1.
// There are one or more Regions formed among N cities.
// A Region is formed in such way that you can travel between any two cities
// in the region that are connected directly and indirectly.
// Your task is to findout the number of regions formed between N cities.
// Input Format:
// -------------
// Line-1: Two space separated integers N and M, number of cities and routes
// Next M lines: Two space separated integers city1, city2.
// Output Format:
// --------------
// Print an integer, number of regions formed.
// Sample Input-1:
// ---------------
// 5 4
// 0 1
// 0 2
// 1 2
// 3 4
// Sample Output-1:
// ----------------
// 2
// Sample Input-2:
// ---------------
// 5 6
// 0 1
// 0 2
// 2 3
// 1 2
// 1 4
// 2 4
// Sample Output-2:
// ----------------
// 1
// Note: Look HINT for explanation.
import java.util.*;
class j{
static List<List<Integer>> adj=new ArrayList<>();
static void dfs(int i,boolean[] vis){
vis[i]=true;
for(int j:adj.get(i)){
if(vis[j]==false){
dfs(j,vis);
}
}
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int e=sc.nextInt();
int[][] g=new int[e][2];
for(int i=0;i<e;i++){
g[i][0]=sc.nextInt();
g[i][1]=sc.nextInt();
}
for(int i=0;i<n;i++){
adj.add(new ArrayList<>());
}
for(int i[]:g){
adj.get(i[0]).add(i[1]);
adj.get(i[1]).add(i[0]);
}
boolean[] vis=new boolean[n];
int ans=0;
for(int i=0;i<n;i++){
if(vis[i]==false){
ans++;
dfs(i,vis);
}
}
System.out.println(ans);
}
}