684. Redundant Connection
- Redundant Connection python solution
题目描述
n this problem, a tree is an undirected graph that is connected and has no cycles.
The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, …, N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.
Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.
解析
看例子 [1, 2], [1, 3], [2, 3],
1
/
2 - 3
最开始有三个不相邻的集合1, 2, 3.
边 [1,2] 表示1,2在一个集合内
边[1,3] 表示1,3在一个集合内
边 [2,3] 表示 2 , 3在一个集合内。
class Solution:
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
parent=[0]*len(edges)
def find(x):
if parent[x]==0:
return x
parent[x]=find(parent[x])
return parent[x]
def union(x,y):
rootx=find(x)
rooty=find(y)
if rootx==rooty:
return False
else:
parent[rootx]=rooty
return True
for x,y in edges:
if not union(x-1,y-1):
return [x,y]
Reference
https://leetcode.com/problems/redundant-connection/discuss/123819/Union-Find-with-Explanations-(Java-Python)