I am writing the dfs in Python with discovery and finish time, etc. And the code below works fine:
def depth_first_search(graph, s):
p = dict.fromkeys(graph.keys()) # parent pointers
d = dict.fromkeys(graph.keys()) # discovery time
f = dict.fromkeys(graph.keys()) # finish time
visited = []
time = [0]
def dfs(node):
visited.append(node)
time[0] += 1
d[node] = time[0]
for v in graph[node]:
if v not in visited:
p[v] = node
dfs(v)
time[0] += 1
f[node] = time[0]
dfs(s)
return (p, d, f, visited)
However, when I change time = [0]
to time = 0
. The code breaks and says "local variable 'time' referenced before assignment".
My question is, why there is no same error when I use the time
var as a list?
I tried the time
var to be both a list and a single var.