DEV Community

Ashutosh Sarangi
Ashutosh Sarangi

Posted on

1 1 1 1 1

Only BFS and DFS in Graph using Javascript

This article is a simple part of the graph where we are just doing BFS and DFS Traversal using both Graph approaches

  1. using adjacent Matrix (BFS)
  2. using an Adjacent List (DFS)
const adjMatrix = [
    [0, 1, 1, 0, 0],
    [1, 0, 0, 1, 0],
    [1, 0, 0, 0, 1],
    [0, 1, 0, 0, 1],
    [0, 0, 1, 1, 0]
];

const BFS = () => {
    const q = [0];
    const visited = [0];
    let path = '';

    while(q.length) {
        const value = q.shift();
        path += value;

        for(let j = 0; j< adjMatrix.length; j++) {
// j Means the Node present / not in visited List
            if (adjMatrix[value][j] && visited.indexOf(j) < 0) {
                q.push(j);
                visited.push(j);
            }
        }
    }
    console.log(path);
}

BFS();

// 01234
Enter fullscreen mode Exit fullscreen mode
const adjList = {
    0: [1, 2],
    1: [0, 3],
    2: [0, 4],
    3: [1, 4],
    4: [2, 3]
}

const DFS = () => {
    const stack = [0];
    const visited = [0];
    let path = '';

    while(stack.length) {
        const value = stack.pop();
        path += value;

        for(let item of adjList[value]) {
            if (visited.indexOf(item) < 0) {
                stack.push(item);
                visited.push(item);
            }
        }
    }
    console.log(path);
}

DFS();// 02431
Enter fullscreen mode Exit fullscreen mode

For a more detailed article on Graph feel free to check out the below link.

Graphs Data Structure using Javascript

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay