Leetcode Leetcode 684. Redundant connection (python)

Topic:

In this problem, the tree refers to a connected and acyclic undirected graph.
Enter a graph that 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 of edges. The elements of each edge are a pair of [u, v], satisfying u <v, representing the edges of the undirected graph connecting vertices u and v.
Return an edge that can be deleted so that the resulting graph is 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 satisfy 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

Solution:

This question template comes from the merge check template

This question is a similar question that is the most basic problem of judging whether a ring exists. The
tree is a connected and acyclic undirected graph.
After an additional edge is added to the tree, a ring will appear.
Therefore, the additional edge is the resulting ring. Emerging edge

We can
judge two nodes each time a new edge is added :

If two nodes are not connected when no edges are added (the root
nodes are different), it means that the two nodes belong to different connected components.
If the merging does not form a ring, connect the two nodes (merge)

If the two nodes are already
connected when no edge is added (the root node is the same), it means that the two nodes belong to the same connected component.
If they are combined, they will form a ring, just return to this edge.

Finally, if the loop is not formed after all traversal,
return an empty list

Code:

class UnionFind:
    def __init__(self):
        """
        记录每个节点的父节点
        """
        self.father = {
    
    }
    
    def find(self,x):
        """
        查找根节点
        路径压缩
        """
        root = x

        while self.father[root] != None:
            root = self.father[root]
         
        return root
    
    def merge(self,x,y):
        """
        合并两个节点
        """
        root_x,root_y = self.find(x),self.find(y)
        
        if root_x != root_y:
            self.father[root_x] = root_y

    def is_connected(self,x,y):
        """
        判断两节点是否相连
        """
        return self.find(x) == self.find(y)

    def add(self,x):
        """
        添加新节点
        """
        if x not in self.father:
            self.father[x] = None


class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        uf = UnionFind()
        for i in range(1, len(edges) + 1):
            uf.add(i)

        for node1, node2 in edges:
            if uf.is_connected(node1, node2) is False:
                uf.merge(node1, node2)
            else:
                return [node1, node2]

        return []

Result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112727790