-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1319_Number of Operations to Make Network Connected.cpp
- Loading branch information
1 parent
19be55f
commit dbb6a58
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
Graph/1319_Number of Operations to Make Network Connected.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
class Solution { | ||
void dfs(vector<int> adj[], vector<bool> &visited, int src) | ||
{ | ||
visited[src] = true; | ||
for(int i : adj[src]){ | ||
if(!visited[i]){ | ||
dfs(adj, visited, i); | ||
} | ||
} | ||
} | ||
public: | ||
int makeConnected(int n, vector<vector<int>>& arr) { | ||
int len = arr.size(); | ||
if(len<n-1) return -1; | ||
vector<int> adj[n]; | ||
for(auto v : arr) | ||
{ | ||
adj[v[0]].push_back(v[1]); | ||
adj[v[1]].push_back(v[0]); | ||
} | ||
vector<bool> visited(n, false); | ||
int ans = 0; | ||
for(int i=0; i<n; i++) | ||
if(!visited[i]) | ||
{ | ||
dfs(adj, visited, i); | ||
ans++; | ||
} | ||
return ans - 1; | ||
} | ||
}; | ||
|
||
|