261 Graph Valid Tree
a----b
| |
c----d
a---.b
| .
. |
c---.ddef validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
g = {i: set() for i in range(0, n)}
for s, e in edges:
g[s].add(e)
g[e].add(s)
def cyclic(root, n):
visited = set()
stack = [root]
while stack:
top = stack.pop()
if top in visited:
return True
visited.add(top)
for neighbor in g[top]:
if (neighbor not in visited):
stack.append(neighbor)
return len(visited) != n
return not cyclic(0, n)Last updated