Problem: https://leetcode.com/problems/graph-valid-tree/
Use DFS to locate if all nodes are connected and no loop exists.
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
seen = [False] * n
visited = 0
stack = [0]
graph = defaultdict(set)
for a, b in edges:
graph[a].add(b)
graph[b].add(a)
while stack:
a = stack.pop()
if seen[a]:
return False
visited += 1
seen[a] = True
for b in graph[a]:
stack.append(b)
graph[b].remove(a)
return visited == n
No comments:
Post a Comment