-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmakeNetworkConnected.java
More file actions
41 lines (29 loc) · 979 Bytes
/
makeNetworkConnected.java
File metadata and controls
41 lines (29 loc) · 979 Bytes
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
class Solution {
private void dfs(List<Integer> g[], int x, boolean v[]){
v[x] = true;
for(int i = 0; i < g[x].size(); i++){
if(v[g[x].get(i)] == false)
dfs(g, g[x].get(i), v);
}
}
public int makeConnected(int n, int[][] conn) {
if(conn.length < n-1)
return -1;
List<Integer>[] g = new ArrayList[n];
for(int i = 0; i < n; i++)
g[i] = new ArrayList<Integer>();
for(int i = 0; i < conn.length; i++){
g[conn[i][0]].add(conn[i][1]);
g[conn[i][1]].add(conn[i][0]);
}
boolean[] visited = new boolean[n];
int comp = 0;
for(int i = 0; i < n; i++){
if(visited[i] == false){
dfs(g, i, visited);
comp++;
}
}
return comp-1;
}
}