Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Created April 6, 2020 02:14
Show Gist options
  • Save nhudinhtuan/f74e2353b6ec0ae7d29a2c65a11bcf92 to your computer and use it in GitHub Desktop.
Save nhudinhtuan/f74e2353b6ec0ae7d29a2c65a11bcf92 to your computer and use it in GitHub Desktop.
DFS Iterating
# graph is represented by adjacency list: List[List[int]]
# s: start vertex
def dfs_iterating(graph, s):
# set is used to mark visited vertices
visited = set()
# create a stack for DFS
stack = []
# Push vertex s to the stack
stack.append(s)
while stack:
current_vertex = stack.pop()
# Stack may contain same vertex twice. So
# we need to print the popped item only
# if it is not visited.
if current_vertex not in visited:
print(current_vertex)
visited.add(current_vertex)
# Get all adjacent vertices of current_vertex
# If an adjacent has not been visited, then push it to stack
for v in graph[current_vertex]:
if v not in visited:
stack.append(v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment