Values never "change back" to a previous value during recursion. Since integers are immutable, they are assigned a new value (replacing the old) in each recursion step: c=c+1
. Since lists are mutable, they can have an element appended to the existing value (modifying the old) in each recursion step: te.append(node)
.
The simplest change is to create and assign a new value for the list as well:
def dfs(node,visited,te,c=0):
if visited[node]==0:
visited[node]=1
te = te + [node] # create new list on each recursive step
c = c + 1
print(te)
if node in king:
for nei in king[node]:
if visited[nei]==0:
dfs(nei, visited, te, c)
Such errors can be avoided by using a tuple instead of a list. A tuple cannot be appended to.
Alternatively, create a copy when passing the list on:
def dfs(node,visited,te,c=0):
if visited[node]==0:
visited[node]=1
te.append(node)
c = c + 1
print(te)
if node in king:
for nei in king[node]:
if visited[nei]==0:
# copy mutable value before passing it on
dfs(nei, visited, te.copy(), c)
Or remove the appended value when done with it:
def dfs(node,visited,te,c=0):
if visited[node]==0:
visited[node]=1
te.append(node)
c = c + 1
print(te)
if node in king:
for nei in king[node]:
if visited[nei]==0:
dfs(nei, visited, te, c)
te.pop() # remove previously appended element