Skip to content

Instantly share code, notes, and snippets.

@danielcodes
Created April 6, 2020 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielcodes/118f2fca9f7c62a7a79e0d11b0496b60 to your computer and use it in GitHub Desktop.
Save danielcodes/118f2fca9f7c62a7a79e0d11b0496b60 to your computer and use it in GitHub Desktop.
261. Graph vaild tree
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