-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack-dfs.html
More file actions
344 lines (329 loc) · 21.8 KB
/
Copy pathstack-dfs.html
File metadata and controls
344 lines (329 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Depth-First Search with a Stack: Graph Traversal Explained | EasyStack</title>
<meta name="description" content="Learn how depth-first search (DFS) uses a stack to traverse graphs and trees. Understand the iterative DFS algorithm, compare it to recursive DFS, and see code examples." />
<meta name="keywords" content="DFS stack, depth first search, iterative DFS, graph traversal, DFS algorithm, stack graph traversal, BFS vs DFS" />
<meta name="author" content="Arun Neupane" />
<meta name="robots" content="index, follow" />
<link rel="canonical" href="https://easystack.netlify.app/stack-dfs" />
<meta name="theme-color" content="#F2F2F7">
<meta name="google-adsense-account" content="ca-pub-1708134460872611">
<meta property="og:title" content="Depth-First Search with a Stack: Graph Traversal Explained" />
<meta property="og:description" content="Learn how depth-first search (DFS) uses a stack to traverse graphs and trees. Understand the iterative DFS algorithm, compare it to recursive DFS, and see code examples." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://easystack.netlify.app/stack-dfs" />
<meta property="og:image" content="https://easystack.netlify.app/images/social-card.png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:site_name" content="EasyStack" />
<meta property="og:locale" content="en_US" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Depth-First Search with a Stack: Graph Traversal Explained" />
<meta name="twitter:description" content="Learn how depth-first search (DFS) uses a stack to traverse graphs and trees. Understand the iterative DFS algorithm, compare it to recursive DFS, and see code examples." />
<link rel="icon" href="./images/stack-fav.png" type="image/x-icon">
<link rel="apple-touch-icon" href="./images/stack-fav.png">
<link rel="stylesheet" href="./hig.css">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "Depth-First Search with a Stack: Graph Traversal Explained",
"description": "Learn how depth-first search (DFS) uses a stack to traverse graphs and trees. Understand the iterative DFS algorithm, compare it to recursive DFS, and see code examples.",
"author": {"@type": "Person", "name": "Arun Neupane", "url": "https://arunneupane.netlify.app/"},
"publisher": {"@type": "Organization", "name": "EasyStack", "url": "https://easystack.netlify.app", "logo": {"@type": "ImageObject", "url": "https://easystack.netlify.app/images/stack-fav.png", "width": 512, "height": 512}},
"datePublished": "2026-09-01",
"dateModified": "2026-09-01",
"mainEntityOfPage": "https://easystack.netlify.app/stack-dfs"
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://easystack.netlify.app/"},
{"@type": "ListItem", "position": 2, "name": "DFS with a Stack", "item": "https://easystack.netlify.app/stack-dfs"}
]
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "Why does DFS use a stack?",
"acceptedAnswer": {"@type": "Answer", "text": "DFS explores as deep as possible along each branch before backtracking. A stack naturally supports this because LIFO order means the most recently discovered node is explored next. This matches the depth-first behavior perfectly."}
},
{
"@type": "Question",
"name": "Is iterative DFS faster than recursive DFS?",
"acceptedAnswer": {"@type": "Answer", "text": "Both have O(V + E) time complexity. Iterative DFS avoids function call overhead and stack overflow risk for very deep graphs. Recursive DFS is more readable but limited by the call stack size. In practice, the difference is negligible for small to medium graphs."}
},
{
"@type": "Question",
"name": "What is the space complexity of DFS?",
"acceptedAnswer": {"@type": "Answer", "text": "DFS uses O(V) space for the visited set and O(V) for the stack in the worst case (a line graph). For balanced trees, the stack depth is O(log V). This is better than BFS which always uses O(V) for the queue."}
},
{
"@type": "Question",
"name": "When should I use DFS over BFS?",
"acceptedAnswer": {"@type": "Answer", "text": "Use DFS when you need to explore all paths, detect cycles, find connected components, perform topological sort, or solve maze/puzzle problems. Use BFS when you need the shortest path in unweighted graphs or level-order traversal."}
}
]
}
</script>
</head>
<body>
<a class="skip-link" href="#main">Skip to content</a>
<header class="topbar"><div class="shell topbar__inner">
<a class="brand" href="./"><span class="brand__mark brand__mark--logo"><img src="./images/stack.gif" alt="" width="30" height="30"></span> EasyStack</a>
<nav aria-label="Primary"><ul class="nav-links desktop-links">
<li><a href="./">Visualizer</a></li><li><a href="./guides">Guides</a></li><li><a href="./stack-visualizer">Tool</a></li><li><a href="./stack-frame-visualizer">Call Stack</a></li><li><a href="./stack-interview">Interview</a></li>
</ul></nav>
<button class="theme-toggle" id="themeToggle" type="button" title="Toggle dark mode"></button>
<button class="nav-toggle" id="navToggle" type="button" aria-label="Menu" aria-expanded="false" aria-controls="navLinks"><span></span><span></span><span></span></button>
<ul class="nav-links nav-mobile" id="navLinks">
<li><a href="./">Visualizer</a></li><li><a href="./guides">All Guides</a></li><li><a href="./stack-operations">Stack Operations</a></li><li><a href="./stack-visualizer">Advanced Tool</a></li><li><a href="./stack-frame-visualizer">Call Stack Visualizer</a></li><li><a href="./stack-complexity">Complexity</a></li><li><a href="./stack-interview">Interview Problems</a></li><li><a href="./about">About</a></li>
</ul>
</div></header>
<main id="main">
<section class="hero hero--guide">
<div class="shell">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>
<li><a href="./">Home</a></li>
<li aria-current="page">DFS with a Stack</li>
</ol></nav>
<h1>Graph Algorithms</h1>
<p class="hero__sub">Depth-first search is one of the most fundamental graph algorithms, and it runs on a stack. Learn the iterative approach, compare it to recursion, and see where DFS is used.</p>
</div>
</section>
<section class="guide-content">
<div class="shell guide-layout">
<aside class="guide-sidebar" aria-label="On this page">
<nav class="toc">
<h2>On this page</h2>
<ul>
<li><a href="#what-is-dfs">What Is DFS</a></li>
<li><a href="#dfs-uses-stack">DFS Uses a Stack</a></li>
<li><a href="#iterative-algorithm">Iterative DFS Algorithm</a></li>
<li><a href="#dfs-graph-example">DFS on a Graph</a></li>
<li><a href="#dfs-binary-tree">DFS on a Binary Tree</a></li>
<li><a href="#recursive-vs-iterative">Recursive vs Iterative DFS</a></li>
<li><a href="#dfs-applications">DFS Applications</a></li>
<li><a href="#code-examples">Code Examples</a></li>
<li><a href="#complexity">Time and Space Complexity</a></li>
<li><a href="#faq">FAQ</a></li>
</ul>
</nav>
</aside>
<article class="guide-article">
<section id="what-is-dfs">
<h2>What Is DFS</h2>
<p>Depth-first search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking. It starts at a source node, marks it as visited, then recursively visits every unvisited neighbor. When it reaches a node with no unvisited neighbors, it backtracks to the previous node and continues.</p>
<p>DFS produces a traversal order that goes deep before going wide. This makes it useful for exploring all paths, detecting cycles, and solving problems that require exploring the full depth of a structure.</p>
</section>
<section id="dfs-uses-stack">
<h2>DFS Uses a Stack</h2>
<p>The connection between DFS and stacks is direct: the algorithm always processes the most recently discovered node next, which is exactly LIFO behavior. In the recursive version, the call stack acts as the stack. In the iterative version, you use an explicit stack data structure.</p>
<p>When you push a node's neighbors onto the stack, the last neighbor pushed is the first one explored. This is what creates the depth-first behavior: you go as deep as possible down one path before trying another.</p>
</section>
<section id="iterative-algorithm">
<h2>Iterative DFS Algorithm</h2>
<p>Here is the step-by-step algorithm:</p>
<ol>
<li>Push the starting node onto the stack.</li>
<li>While the stack is not empty, pop a node.</li>
<li>If the node has not been visited, mark it as visited and process it.</li>
<li>Push all unvisited neighbors of this node onto the stack.</li>
<li>Repeat from step 2.</li>
</ol>
<p>Important: you mark nodes as visited when you pop them, not when you push them. This prevents duplicate processing but means the same node may be pushed multiple times. If you mark on push instead, you avoid duplicates but change the traversal order slightly.</p>
</section>
<section id="dfs-graph-example">
<h2>DFS on a Graph</h2>
<p>Consider this graph:</p>
<div class="code-block">
<pre><code>A -- B -- D
| |
C -- E -- F</code></pre>
</div>
<p>Starting from A, one possible DFS traversal is: A, B, D, E, C, F. The stack trace would be:</p>
<div class="code-block">
<pre><code>Push A
Pop A (visit A), push B, C
Pop C (visit C), push E
Pop E (visit E), push B, F
Pop F (visit F)
Pop B (visit B), push D
Pop D (visit D)
Stack empty. Done.
Traversal: A, C, E, F, B, D</code></pre>
</div>
<p>Note that the exact order depends on the order in which neighbors are pushed. Different push orders produce different valid DFS traversals.</p>
</section>
<section id="dfs-binary-tree">
<h2>DFS on a Binary Tree</h2>
<p>DFS on a binary tree has three common orderings based on when you process the node relative to its children:</p>
<ul>
<li><strong>Pre-order:</strong> Process node, then left subtree, then right subtree.</li>
<li><strong>In-order:</strong> Process left subtree, then node, then right subtree (gives sorted order for BSTs).</li>
<li><strong>Post-order:</strong> Process left subtree, then right subtree, then node (used for deletion and expression evaluation).</li>
</ul>
<p>For iterative in-order DFS, use a stack and a pointer that moves left until it cannot, then pops and processes, then moves right.</p>
</section>
<section id="recursive-vs-iterative">
<h2>Recursive DFS vs Iterative DFS</h2>
<table class="table table--hig">
<thead>
<tr>
<th>Aspect</th>
<th>Recursive DFS</th>
<th>Iterative DFS</th>
</tr>
</thead>
<tbody>
<tr>
<td>Readability</td>
<td>Clean and concise</td>
<td>Slightly more verbose</td>
</tr>
<tr>
<td>Stack Used</td>
<td>Call stack (implicit)</td>
<td>Explicit stack (heap memory)</td>
</tr>
<tr>
<td>Stack Overflow Risk</td>
<td>Yes, for deep graphs</td>
<td>No, grows on heap</td>
</tr>
<tr>
<td>Memory Control</td>
<td>Limited by stack size</td>
<td>Full control over allocation</td>
</tr>
<tr>
<td>Performance</td>
<td>Function call overhead</td>
<td>Slightly faster (no call overhead)</td>
</tr>
<tr>
<td>Time Complexity</td>
<td>O(V + E)</td>
<td>O(V + E)</td>
</tr>
</tbody>
</table>
</section>
<section id="dfs-applications">
<h2>DFS Applications</h2>
<ul>
<li><strong>Cycle detection:</strong> If DFS encounters a node that is already in the current recursion stack, a cycle exists in a directed graph.</li>
<li><strong>Topological sort:</strong> DFS-based topological sort processes nodes in reverse finish order. Used for scheduling tasks with dependencies.</li>
<li><strong>Connected components:</strong> Run DFS from each unvisited node in an undirected graph. Each run discovers one connected component.</li>
<li><strong>Path finding:</strong> DFS can find if a path exists between two nodes. It finds one valid path but not necessarily the shortest.</li>
<li><strong>Maze solving:</strong> DFS explores all possible paths in a maze until it finds the exit.</li>
<li><strong>Strongly connected components:</strong> Kosaraju's and Tarjan's algorithms use DFS to find SCCs in directed graphs.</li>
</ul>
</section>
<section id="code-examples">
<h2>Code Examples</h2>
<h3>Python</h3>
<div class="code-block">
<pre><code>def dfs_iterative(graph, start):
visited = set()
stack = [start]
order = []
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
stack.append(neighbor)
return order
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'E'],
'D': ['B'],
'E': ['B', 'C', 'F'],
'F': ['E']
}
print(dfs_iterative(graph, 'A'))</code></pre>
</div>
<h3>JavaScript</h3>
<div class="code-block">
<pre><code>function dfsIterative(graph, start) {
const visited = new Set();
const stack = [start];
const order = [];
while (stack.length > 0) {
const node = stack.pop();
if (!visited.has(node)) {
visited.add(node);
order.push(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
stack.push(neighbor);
}
}
}
}
return order;
}
const graph = {
A: ['B', 'C'],
B: ['A', 'D', 'E'],
C: ['A', 'E'],
D: ['B'],
E: ['B', 'C', 'F'],
F: ['E']
};
console.log(dfsIterative(graph, 'A'));</code></pre>
</div>
</section>
<section id="complexity">
<h2>Time and Space Complexity</h2>
<p><strong>Time:</strong> O(V + E) where V is the number of vertices and E is the number of edges. Each vertex is processed once and each edge is examined once.</p>
<p><strong>Space:</strong> O(V) for the visited set and the stack. In the worst case (a line graph), the stack holds all V vertices. For balanced trees, the stack depth is O(log V).</p>
<p>Compare this to BFS which also runs in O(V + E) time but always uses O(V) space for the queue regardless of graph structure. DFS can be more space-efficient on graphs that are deep but narrow.</p>
</section>
<section id="faq" class="faq-section">
<h2>Frequently Asked Questions</h2>
<div class="faq-item">
<h3>Why does DFS use a stack?</h3>
<p>DFS explores as deep as possible along each branch before backtracking. A stack naturally supports this because LIFO order means the most recently discovered node is explored next. This matches the depth-first behavior perfectly.</p>
</div>
<div class="faq-item">
<h3>Is iterative DFS faster than recursive DFS?</h3>
<p>Both have O(V + E) time complexity. Iterative DFS avoids function call overhead and stack overflow risk for very deep graphs. Recursive DFS is more readable but limited by the call stack size. In practice, the difference is negligible for small to medium graphs.</p>
</div>
<div class="faq-item">
<h3>What is the space complexity of DFS?</h3>
<p>DFS uses O(V) space for the visited set and O(V) for the stack in the worst case (a line graph). For balanced trees, the stack depth is O(log V). This is better than BFS which always uses O(V) for the queue.</p>
</div>
<div class="faq-item">
<h3>When should I use DFS over BFS?</h3>
<p>Use DFS when you need to explore all paths, detect cycles, find connected components, perform topological sort, or solve maze/puzzle problems. Use BFS when you need the shortest path in unweighted graphs or level-order traversal.</p>
</div>
</section>
</article>
</div>
</section>
</main>
<footer class="footer"><div class="shell"><div class="footer__grid">
<div><div class="footer__brand"><span class="brand__mark brand__mark--logo"><img src="./images/stack.gif" alt="" width="24" height="24"></span> EasyStack</div><p class="footer__about">A free, interactive stack data structure visualizer with comprehensive guides.</p><div class="footer-social"><a href="https://github.com/arundada9000" target="_blank" rel="noopener noreferrer" aria-label="GitHub"><img src="./images/stack-fav.png" alt="GitHub" style="width:19px;height:19px;border-radius:4px"></a></div></div>
<div><h4>Guides</h4><ul><li><a href="./stack-operations">Stack Operations</a></li><li><a href="./push-pop">Push and Pop</a></li><li><a href="./stack-complexity">Time Complexity</a></li><li><a href="./stack-analogies">Real-World Analogies</a></li><li><a href="./call-stack">The Call Stack</a></li></ul></div>
<div><h4>Learn</h4><ul><li><a href="./guides">All Guides</a></li><li><a href="./array-stack">Array Implementation</a></li><li><a href="./linked-list-stack">Linked List Stack</a></li><li><a href="./stack-memory">Stack Memory</a></li><li><a href="./monotonic-stack">Monotonic Stack</a></li></ul></div>
<div><h4>Site</h4><ul><li><a href="./about">About</a></li><li><a href="./contact">Contact</a></li><li><a href="./privacy">Privacy Policy</a></li><li><a href="https://github.com/arundada9000/Stack" target="_blank" rel="noopener">Source Code</a></li></ul></div>
</div><div class="footer__bottom"><span>Copyright <span data-year>2026</span> EasyStack. Made by Arun Neupane.</span><span>Free forever. No sign-up. Fully offline-ready PWA.</span></div></div></footer>
<script src="./hig.js"></script>
</body>
</html>