def dfs1(graph, v, visited):
visited[v] = True
print(v, end = ' ')
for i in graph[v]:
if not visited[i]:
dfs1(graph, i, visited)
return 0
def dfs2(graph, v, visited):
stack = []
stack.append(1)
visited[1] = True
while stack:
now = stack.pop()
print(now, end = ' ')
for i in graph[now][::-1]:
if not visited[i]:
stack.append(i)
visited[i] = True
return 0
def dfs3(graph, v, visited):
stack = []
stack.append(1)
visited[1] = True
while stack:
now = stack.pop()
print(now, end = ' ')
for i in graph[now]:
if not visited[i]:
stack.append(i)
visited[i] = True
return 0
graph = [
[],
[2, 3, 8],
[1, 7],
[1, 4, 5],
[3, 5],
[3, 4],
[7],
[2, 6, 8],
[1, 7]
]
visited = [False] * 9
print('dfs1 rec')
dfs1(graph, 1, visited)
print('')
visited = [False] * 9
print('dfs2 stack-rev')
dfs2(graph, 1, visited)
print('')
visited = [False] * 9
print('dfs3 stack')
dfs3(graph, 1, visited)
print('')