-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1319. Number of Operations to Make Network Connected.java
More file actions
49 lines (41 loc) · 1.24 KB
/
1319. Number of Operations to Make Network Connected.java
File metadata and controls
49 lines (41 loc) · 1.24 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
class Solution {
public int makeConnected(int n, int[][] connections) {
if(connections.length < n-1)
return -1;
ArrayList<ArrayList<Integer>> g = new ArrayList<>();
for(int i = 0; i < n; i++)
{
g.add(new ArrayList<>());
}
for(int i = 0; i < connections.length; i++)
{
int u = connections[i][0];
int v = connections[i][1];
g.get(u).add(v);
g.get(v).add(u);
}
ArrayList<ArrayList<Integer>> comps = new ArrayList<>();
boolean vis[] = new boolean[n];
for(int i = 0; i < n; i++)
{
if(!vis[i])
{
ArrayList<Integer> temp = new ArrayList<>();
dfs(i, temp, vis, g);
comps.add(temp);
}
}
return comps.size() - 1;
}
public static void dfs(int src, ArrayList<Integer> temp, boolean vis[], ArrayList<ArrayList<Integer>> g)
{
vis[src] = true;
temp.add(src);
ArrayList<Integer> nbr = g.get(src);
for(int n : nbr)
{
if(!vis[n])
dfs(n, temp, vis, g);
}
}
}