sandeep03edu

Redundant Connection

Jul 22nd, 2022
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. class Solution {
  2. public:
  3.    
  4.     bool dfs(int i, int par, vector<vector<int>>& graph, vector<bool> &vis, vector<int> &cycle){
  5.         vis[i] = 1;
  6.         cycle.push_back(i);
  7.        
  8.         for(int a : graph[i]){
  9.             if(!vis[a]){
  10.                 if(dfs(a, i,graph, vis, cycle)){
  11.                     return true;
  12.                 }
  13.             }
  14.             else if(par!=a){
  15.                 cycle.push_back(a);
  16.                 return true;
  17.             }
  18.         }
  19.        
  20.         cycle.pop_back();
  21.         return false;
  22.  
  23.     }
  24.        
  25.     vector<int> findRedundantConnection(vector<vector<int>>& edges) {
  26.         int n = edges.size();
  27.        
  28.         vector<bool> vis(n, 0);
  29.         vector<vector<int>> graph(n);
  30.        
  31.         for(auto vec : edges){
  32.             int a = vec[0]-1, b = vec[1]-1;
  33.             graph[a].push_back(b);
  34.             graph[b].push_back(a);
  35.         }
  36.        
  37.         vector<int> ans, cycle;
  38.        
  39.         dfs(0,-1 , graph, vis, cycle);
  40.        
  41.         int last = cycle[cycle.size()-1];
  42.         int i=cycle.size()-1;
  43.        
  44.         unordered_map<int, int> mp;
  45.        
  46.         do{
  47.             mp[cycle[i]]=1;
  48.             i--;
  49.         }
  50.         while(cycle[i]!=last);
  51.        
  52.         for(auto vec : edges){
  53.             int a = vec[0]-1, b = vec[1]-1;
  54.             if(mp[a]==1 && mp[b]==1){
  55.                 ans = vec;
  56.             }
  57.         }
  58.        
  59.         return ans;
  60.     }
  61. };
Advertisement
Add Comment
Please, Sign In to add comment