File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ ProblemLink : https://leetcode.com/problems/redundant-connection/
3
+
4
+ In this problem, a tree is an undirected graph that is connected and has no cycles.
5
+
6
+ You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added.
7
+ The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed.
8
+ The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.
9
+
10
+ Return an edge that can be removed so that the resulting graph is a tree of n nodes.
11
+ If there are multiple answers, return the answer that occurs last in the input.
12
+ */
13
+
14
+ class Solution {
15
+ public:
16
+ int find (int v,vector<int >& parent){
17
+ if (parent[v]==-1 ){
18
+ return v;
19
+ }
20
+ return find (parent[v],parent);
21
+ }
22
+ void Union (int x,int y,vector<int >& parent){
23
+ parent[x]=y;
24
+ }
25
+
26
+ vector<int > findRedundantConnection (vector<vector<int >>& edges) {
27
+ int V = edges.size ();
28
+ vector<int > parent (V+1 ,-1 );
29
+ int v1,v2;
30
+ for (auto x:edges){
31
+ int fromP = find (x[0 ],parent);
32
+ int toP = find (x[1 ],parent);
33
+ if (fromP==toP){
34
+ v1=x[0 ];
35
+ v2=x[1 ];
36
+ }
37
+ else {
38
+ Union (fromP,toP,parent);
39
+ }
40
+ }
41
+ vector<int > ans;
42
+ ans.push_back (v1);
43
+ ans.push_back (v2);
44
+ return ans;
45
+ }
46
+ };
You can’t perform that action at this time.
0 commit comments