Leetcode 261. Graph Valid Tree(python)

Leetcode 261. Graph Valid Tree

  • 题目
  • 解法1:DFS
  • 解法2:BFS
  • 解法3:并查集(union find)
  • 参考链接:

题目

Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false

解法1:DFS

edges构成边需符合两个条件:

  • 所有边构成连通图
  • 所有边不成环
    这边是无向图的环检测,有向图的换检测参见207. Course Schedule
    是否构成连通图的判断:
    构建visited数组,数组长度与节点数相同,构成连通图的必要条件是这个数组中每个元素都被访问
    环检测:
    访问到visited中已经有的元素即为成环。但是由于这边在构建dict时是双向的,所以还需要判断当前节点的parent节点。
class Solution:
    def validTree(self, n: int, edges: List[List[int]]) -> bool:        
        if len(edges) != n-1:
            return False
        memo = collections.defaultdict(list)
        for edge in edges:
            memo[edge[0]].append(edge[1])
            memo[edge[1]].append(edge[0])
        visited = [False]*n
        def helper(curr,parent):
            if visited[curr]:
                return False
            visited[curr] = True
            for val in memo[curr]:
                if val!= parent and not helper(val,curr):
                    return False
            return True
        if not helper(0,-1):
            return False
        for v in visited:
            if not v:
                return False
        return True

解法2:BFS

BFS的判断条件为,当所有的pair被访问结束之后,被访问过的节点数与n相同

class Solution:
    def validTree(self, n: int, edges: List[List[int]]) -> bool:        
        if len(edges) != n - 1:  # Check number of edges.
            return False
 
        # init node's neighbors in dict
        neighbors = collections.defaultdict(list)
        for u, v in edges:
            neighbors[u].append(v)
            neighbors[v].append(u)
 
        # BFS to check whether the graph is valid tree.
        visited = {}
        q = collections.deque([0])
        while q:
            curr = q.popleft()
            visited[curr] = True
            for node in neighbors[curr]:
                if node not in visited:
                    visited[node] = True
                    q.append(node)
 
        return len(visited)==n

解法3:并查集(union find)

留待后续补充

参考链接:

https://www.cnblogs.com/lightwindy/p/8636516.html

你可能感兴趣的:(Leetcode,BFS)