Graph Traversals in Javascript

Graph traversal (also known as graph search) refers to the process of visiting (checking and/or updating) each vertex in a graph. Such traversals are classified by the order in which the vertices are visited.

In JavaScript, the two most common graph traversal algorithms are Breadth-First Search (BFS) and Depth-First Search (DFS). Both algorithms systematically explore graph nodes but use different strategies.

Graph Representation

First, let's create a simple graph using an adjacency list representation:

class Graph {
    constructor() {
        this.adjacencyList = {};
    }
    
    addVertex(vertex) {
        if (!this.adjacencyList[vertex]) {
            this.adjacencyList[vertex] = [];
        }
    }
    
    addEdge(vertex1, vertex2) {
        this.adjacencyList[vertex1].push(vertex2);
        this.adjacencyList[vertex2].push(vertex1);
    }
}

// Create a sample graph
const graph = new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "D");
graph.addEdge("C", "D");

console.log(graph.adjacencyList);
{ A: [ 'B', 'C' ], B: [ 'A', 'D' ], C: [ 'A', 'D' ], D: [ 'B', 'C' ] }

Depth-First Search (DFS)

DFS explores as far as possible along each branch before backtracking. It uses a stack (or recursion) to keep track of vertices:

Graph.prototype.dfs = function(start) {
    const result = [];
    const visited = {};
    const adjacencyList = this.adjacencyList;
    
    function dfsHelper(vertex) {
        if (!vertex) return null;
        
        visited[vertex] = true;
        result.push(vertex);
        
        adjacencyList[vertex].forEach(neighbor => {
            if (!visited[neighbor]) {
                return dfsHelper(neighbor);
            }
        });
    }
    
    dfsHelper(start);
    return result;
};

// Test DFS
console.log("DFS traversal from A:", graph.dfs("A"));
DFS traversal from A: [ 'A', 'B', 'D', 'C' ]

Breadth-First Search (BFS)

BFS explores all vertices at the current depth before moving to vertices at the next depth level. It uses a queue:

Graph.prototype.bfs = function(start) {
    const queue = [start];
    const result = [];
    const visited = {};
    let currentVertex;
    
    visited[start] = true;
    
    while (queue.length) {
        currentVertex = queue.shift();
        result.push(currentVertex);
        
        this.adjacencyList[currentVertex].forEach(neighbor => {
            if (!visited[neighbor]) {
                visited[neighbor] = true;
                queue.push(neighbor);
            }
        });
    }
    
    return result;
};

// Test BFS
console.log("BFS traversal from A:", graph.bfs("A"));
BFS traversal from A: [ 'A', 'B', 'C', 'D' ]

Comparison

Algorithm Data Structure Time Complexity Space Complexity
DFS Stack/Recursion O(V + E) O(V)
BFS Queue O(V + E) O(V)

Complete Example

// Create a larger graph for demonstration
const largerGraph = new Graph();
["A", "B", "C", "D", "E", "F"].forEach(vertex => {
    largerGraph.addVertex(vertex);
});

largerGraph.addEdge("A", "B");
largerGraph.addEdge("A", "C");
largerGraph.addEdge("B", "D");
largerGraph.addEdge("C", "E");
largerGraph.addEdge("D", "E");
largerGraph.addEdge("D", "F");
largerGraph.addEdge("E", "F");

console.log("Graph structure:", largerGraph.adjacencyList);
console.log("DFS from A:", largerGraph.dfs("A"));
console.log("BFS from A:", largerGraph.bfs("A"));
Graph structure: {
  A: [ 'B', 'C' ],
  B: [ 'A', 'D' ],
  C: [ 'A', 'E' ],
  D: [ 'B', 'E', 'F' ],
  E: [ 'C', 'D', 'F' ],
  F: [ 'D', 'E' ]
}
DFS from A: [ 'A', 'B', 'D', 'E', 'C', 'F' ]
BFS from A: [ 'A', 'B', 'C', 'D', 'E', 'F' ]

Key Points

DFS is useful for detecting cycles, topological sorting, and pathfinding. BFS is ideal for finding shortest paths in unweighted graphs and level-order traversals.

Conclusion

Graph traversals are fundamental algorithms for exploring graph structures. DFS uses recursion/stack for deep exploration, while BFS uses queues for level-by-level traversal.

Updated on: 2026-03-15T23:18:59+05:30

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements