I was working on the LeetCode problem Graph Valid Tree (#261) and was having some weird issue with Python when using global variables to detect a cycle. Essentially, if I detected a cycle, I wanted to set boolCycle
to True
. However, sometimes, I would print boolCycle
out during the DFS (where it would evaluate to True
), and then after running DFS and it would evaluate to False
. I couldn't figure out why this is happening as boolCycle
is a global variable, and the only change I ever make to it is to set it to True
, so it should remain that way.
I instead came up with a hacky solution where I just created a list called cycle
and added an element to it if there was a cycle, which ended up working. I'm curious as to why modifying the global list works as intended but modifying the global boolean doesn't.
cycle = []
boolCycle = False
def dfs(parent, node):
visited.add(node)
for neighbor in graph[node]:
if neighbor in visited and neighbor != parent:
cycle.append('hello')
boolCycle = True
return
if neighbor not in visited:
dfs(node, neighbor)