"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Only BFS and DFS in Graph using Javascript

Only BFS and DFS in Graph using Javascript

Published on 2024-08-25
Browse:278

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





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) 



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

Graphs Data Structure using Javascript

Release Statement This article is reproduced at: https://dev.to/ashutoshsarangi/only-bfs-and-dfs-in-graph-using-javascript-52pn?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3