-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathdfs.js
More file actions
44 lines (37 loc) · 1.01 KB
/
Copy pathdfs.js
File metadata and controls
44 lines (37 loc) · 1.01 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
// Depth-First Search (DFS) Traversal of a Graph
// Time Complexity: O(V + E), Space Complexity: O(V)
//
// Idea: Explore as far as possible along each branch before backtracking.
// DFS can be implemented using recursion or an explicit stack.
//
// DFS is useful for pathfinding, topological sorting, and detecting cycles.
function dfsTraversal(graph, start) {
const visited = new Set(); // keeps track of visited nodes
const result = []; // stores traversal order
function dfs(node) {
visited.add(node);
result.push(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
dfs(neighbor);
}
}
}
dfs(start);
return result;
}
// Quick test example
if (require.main === module) {
// Example graph represented as adjacency list
const graph = {
A: ["B", "C"],
B: ["D", "E"],
C: ["F"],
D: [],
E: ["F"],
F: [],
};
console.log(dfsTraversal(graph, "A"));
// Expected output: ['A', 'B', 'D', 'E', 'F', 'C']
}
module.exports = dfsTraversal;