Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d012f3a

Browse files
Added Redundant connections problem from Leetcode-684 (#192)
Added Problem Link at start
1 parent 44419fa commit d012f3a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎C++/RedundantConnection.cpp‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /