Created
April 6, 2020 12:38
-
-
Save danielcodes/118f2fca9f7c62a7a79e0d11b0496b60 to your computer and use it in GitHub Desktop.
261. Graph vaild tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
def solve(n, edges): | |
def has_cycle(node, parent, adj, visited): | |
visited.add(node) | |
for n in adj[node]: | |
# node has been visited and not the parent | |
if n in visited and n != parent: | |
return True | |
# process neighbor, dont visit parent | |
if n not in visited and has_cycle(n, node, adj, visited): | |
return True | |
return False | |
# create adj list | |
adj = defaultdict(list) | |
for edge in edges: | |
x, y = edge | |
adj[x].append(y) | |
adj[y].append(x) | |
# better approach, check for cycles | |
# and it is a tree if, every node has been visited | |
visited = set() | |
if has_cycle(0, -1, adj, visited): | |
return False | |
return len(visited) == n | |
n = 5 | |
edges = [[0, 1], [0, 2], [0, 3], [1, 4]] | |
# edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]] | |
print(solve(n, edges)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment