-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1319.number-of-operations-to-make-network-connected.cpp
More file actions
39 lines (33 loc) · 1.21 KB
/
1319.number-of-operations-to-make-network-connected.cpp
File metadata and controls
39 lines (33 loc) · 1.21 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
class Solution {
public:
int makeConnected(int n, vector<vector<int>>& connections) {
if(connections.size() < n-1)
return -1;
vector<int> visited(n, false);
int count = 0;
vector<vector<int>> graph = createGraph(connections, n);
auto startNode = find(visited.begin(), visited.end(), false);
while(startNode != visited.end()){
dfs(graph, visited, startNode - visited.begin());
count++;
startNode = find(visited.begin(), visited.end(), false);
}
return count-1;
}
vector<vector<int>> createGraph(vector<vector<int>> connections, int n){
vector<vector<int>> graph(n);
for(auto connection : connections){
graph[connection[0]].push_back(connection[1]);
graph[connection[1]].push_back(connection[0]);
}
return graph;
}
void dfs(vector<vector<int>>& isConnected, vector<int>& visited, int node){
if(visited[node])
return;
visited[node] = true;
for(auto i : isConnected[node])
if(!visited[i] && i!= node)
dfs(isConnected, visited, i);
}
};