JavaScript Program to Implement Depth-First Search

JavaScript Program to Implement Depth-First Search

Depth-First Search, often abbreviated as DFS, is a fundamental algorithm used to traverse or search through graphs and trees. Unlike Breadth-First Search, which explores neighbors level by level, DFS dives as deep as possible along a path before backtracking. This makes it especially useful for solving problems that require exploring all possibilities, such as maze solving, puzzle games, network analysis, or even analyzing social connections.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

For beginners, understanding DFS is an excellent way to learn about recursion, stacks, and graph structures. It demonstrates how computers can explore complex networks systematically. With DFS, you can efficiently traverse connected nodes, detect cycles, and even implement algorithms like topological sorting or pathfinding. By learning DFS in JavaScript, you get a strong foundation in handling data structures like graphs and trees, which are crucial for many real-world applications.

Program 1: DFS Using Recursion on a Graph

This program demonstrates a simple recursive DFS implementation on a predefined graph.

const graph = {
    A: ['B', 'C'],
    B: ['D', 'E'],
    C: ['F'],
    D: [],
    E: ['F'],
    F: []
};

function dfsRecursive(node, visited = new Set()) {

    if (visited.has(node)) return;

    console.log(node);
    visited.add(node);

    for (let neighbor of graph[node]) {
        dfsRecursive(neighbor, visited);
    }

}

dfsRecursive('A');

This program starts at node A and visits each connected node as deep as possible before backtracking. Beginners can understand recursion as “go deeper, then return when there’s nothing left to explore.” It is useful because it provides a clear and simple way to traverse all nodes in a graph.

Program 2: DFS Using Stack (Iterative Approach)

This example demonstrates DFS without recursion, using a stack instead.

const graphIter = {
    A: ['B', 'C'],
    B: ['D', 'E'],
    C: ['F'],
    D: [],
    E: ['F'],
    F: []
};

function dfsIterative(start) {

    const visited = new Set();
    const stack = [start];

    while (stack.length > 0) {

        const node = stack.pop();

        if (!visited.has(node)) {

            console.log(node);
            visited.add(node);

            for (let neighbor of graphIter[node].slice().reverse()) {
                stack.push(neighbor);
            }

        }

    }

}

dfsIterative('A');

This iterative approach uses a stack to track nodes instead of recursion. Beginners can understand it as “keep a list of nodes to explore and go through them one by one.” It is useful for environments where recursion depth might be limited or when you want more control over traversal.

Program 3: DFS on a Tree Structure

This program shows DFS applied to a simple tree represented as nested objects.

const tree = {

    value: 'A',
    children: [
        { value: 'B', children: [{ value: 'D', children: [] }, { value: 'E', children: [] }] },
        { value: 'C', children: [{ value: 'F', children: [] }] }
    ]

};

function dfsTree(node) {

    console.log(node.value);

    for (let child of node.children) {
        dfsTree(child);
    }

}

dfsTree(tree);

This program traverses a tree structure, visiting each node deeply before moving to siblings. Beginners can visualize it as “explore each branch fully before moving to the next one.” It is useful for scenarios such as parsing JSON, DOM trees, or hierarchical data.

Program 4: DFS to Detect Cycles in a Graph

This example demonstrates how DFS can be used to detect cycles in a graph.

const cyclicGraph = {
    A: ['B'],
    B: ['C'],
    C: ['A'],
    D: ['E'],
    E: []
};

function dfsDetectCycle(node, visited = new Set(), recStack = new Set()) {

    if (!visited.has(node)) {

        visited.add(node);
        recStack.add(node);

        for (let neighbor of cyclicGraph[node]) {

            if (!visited.has(neighbor) && dfsDetectCycle(neighbor, visited, recStack)) return true;
            else if (recStack.has(neighbor)) return true;

        }

    }

    recStack.delete(node);

    return false;

}

console.log(dfsDetectCycle('A') ? "Cycle detected" : "No cycle");

This program tracks a recursion stack to detect cycles. Beginners can understand it as “if you revisit a node currently being explored, there is a cycle.” It is useful for tasks like dependency checks, deadlock detection, and network validation.

Program 5: DFS to Find a Path in a Graph

This program uses DFS to find a path between two nodes.

const graphPath = {
    A: ['B', 'C'],
    B: ['D'],
    C: ['D', 'E'],
    D: ['F'],
    E: [],
    F: []
};

function dfsFindPath(start, target, visited = new Set(), path = []) {

    visited.add(start);
    path.push(start);

    if (start === target) return path;

    for (let neighbor of graphPath[start]) {

        if (!visited.has(neighbor)) {

            const result = dfsFindPath(neighbor, target, visited, path.slice());

            if (result) return result;

        }

    }

    return null;

}

console.log("Path from A to F:", dfsFindPath('A', 'F'));

This program demonstrates DFS applied to find a path from a start node to a target node. Beginners can visualize it as “explore all possibilities until you reach the target.” It is useful for pathfinding in maps, games, or navigation systems.

Frequently Asked Questions (FAQ)

This section answers common questions about DFS in JavaScript.

Q1. What is Depth-First Search?
Depth-First Search is an algorithm that explores a graph by going as deep as possible along each branch before backtracking.

Q2. Can DFS handle cycles in graphs?
Yes, by keeping track of visited nodes or recursion stacks, DFS can handle cycles and even detect them.

Q3. What is the difference between DFS and BFS?
DFS explores deeply along a path before backtracking, while BFS explores neighbors level by level.

Q4. When should I use DFS over BFS?
DFS is often used when you need to explore all possibilities, detect cycles, or work with tree structures.

Q5. What is the time complexity of DFS?
The time complexity is O(V + E), where V is the number of vertices and E is the number of edges in the graph.

Conclusion

Depth-First Search is a versatile algorithm that can explore graphs and trees in a systematic way.

By practicing recursive, iterative, tree traversal, cycle detection, and pathfinding implementations, beginners can build a solid foundation in graph algorithms. DFS teaches key programming concepts such as recursion, stacks, and systematic exploration, which are valuable skills for solving real-world problems in JavaScript.

Scroll to Top