Advertisement
nikunjsoni

1319

Apr 28th, 2021
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int makeConnected(int n, vector<vector<int>>& connections) {
  4.         if(connections.size() < n-1) return -1;
  5.         int components = 0;
  6.        
  7.         vector<vector<int>> g;
  8.         g.resize(n);
  9.         for(auto edge: connections){
  10.             g[edge[0]].push_back(edge[1]);
  11.             g[edge[1]].push_back(edge[0]);
  12.         }
  13.        
  14.         vector<bool> vis(n, false);
  15.         for(int i=0; i<n; i++)
  16.             if(!vis[i])
  17.                 dfs(i, g, vis), components++;
  18.         return components-1;
  19.     }
  20.    
  21.     void dfs(int node, vector<vector<int>> &g, vector<bool> &vis){
  22.         vis[node] = true;
  23.         for(int child: g[node])
  24.             if(!vis[child])
  25.                 dfs(child, g, vis);
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement