684. Redundant connection
In this problem, the tree refers to an undirected graph that is connected and acyclic .
Enter a graph, which consists of a tree with N nodes (the node values do not repeat 1, 2, ..., N) and an additional edge. The two vertices of the additional edge are contained between 1 and N. This additional edge does not belong to an existing edge in the tree.
The resulting graph is a 边
two-dimensional array. Each 边
element is a pair [u, v]
, satisfying u < v
, which represents the edge of the undirected graph connecting the vertices u
and .v
Return an edge that can be deleted, making the resulting graph a tree with N nodes. If there are multiple answers, the last edge in the two-dimensional array is returned. The answer side [u, v]
should meet the same format u < v
.
Example 1:
Input: [[1,2], [1,3], [2,3]] Output: [2,3] Explanation: The given undirected graph is: 1 / \ 2-3
Example 2:
Input: [[1,2], [2,3], [3,4], [1,4], [1,5]] Output: [1,4] Explanation: The given undirected graph is: 5-1-2 | | 4-3
note:
- The size of the input 2D array is from 3 to 1000.
- The integers in the two-dimensional array are between 1 and N, where N is the size of the input array.
class Solution(object): def findRedundantConnection(self, edges): """ :type edges: List[List[int]] :rtype: List[int] """ self.init(len(edges)) ans = [] for u,v in edges: is_success, e2 = self.connect(u, v) if not is_success: ans = e2 return ans def init(self, N): self.father = {} for i in range(1, N+1): self.father[i] = i def connect(self, u, v): f1 = self.find_father(u) f2 = self.find_father(v) if f1 == f2: return False, [u, v] else: self.father[f1] = f2 return True, [] def find_father(self, u): root = u path = [] while self.father[root] != root: path.append(root) root = self.father[root] for p in path: self.father[p] = root return root