Get the latest tech news

Iterative DFS with stack-based graph traversal (2024)


This post explores how to effectively implement an iterative depth-first search (DFS) traversal on a graph with a stack, addressing a common pitfall along the way.

Depth-first search (DFS) on a graph (binary tree or otherwise) is most often implemented recursively, but there are occasions where it may be desirable to consider an iterative approach instead. Specifically, as noted in another blog post, it is easy to fall into the trap of using a stack haphazardly and conducting a graph search that is not truly DFS. As also mentioned in the blog post, both approaches above have the property that replacing the stack by a queue gives a breadth-first search, albeit implemented in a somewhat nonstandard way.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of stack

stack

Photo of Iterative DFS

Iterative DFS

Related news:

News photo

Rethinking the Linux cloud stack for confidential VMs

News photo

SAML Shield: Drop-in protection that works for any stack

News photo

Arm plots move up the stack with push into end-to-end silicon