Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Created April 6, 2020 02:09
Show Gist options
  • Save nhudinhtuan/36b8c9f3216df87874865fd984387aad to your computer and use it in GitHub Desktop.
Save nhudinhtuan/36b8c9f3216df87874865fd984387aad to your computer and use it in GitHub Desktop.
DFS recursive
# graph is represented by adjacency list: List[List[int]]
# s: start vertex
def dfs(graph, s):
# set is used to mark visited vertices
visited = set()
def recur(current_vertex):
print(current_vertex)
# mark it visited
visited.add(current_vertex)
# Recur for all the vertices adjacent to current_vertex
for v in graph[current_vertex]:
if v not in visited:
recur(v)
recur(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment