age-viewer icon indicating copy to clipboard operation
age-viewer copied to clipboard

Sample JavaScript codes for DFS and BFS algorithms

Open aked21 opened this issue 2 years ago • 1 comments

aked21 avatar Oct 11 '22 13:10 aked21

Code for BFS

const bfs = (graph, node) => {
  let visited = [];
  let nodes= [];

  nodes.push(node); 

  while (nodes.length !== 0) { 
    const newNode = nodes.shift(); 
    if (!visited.includes(newNode )) {
      visited.push(newNode ); 
      nodes= [...nodes, ...graph[newNode ]];
    }
  }
  return visited;
};

Code for DFS

const dfs = (graph, node) => {
  let stack= [];
  let queue= [];

  stack.push(node);

  while (stack.length !== 0) {
    const newNode = stack.pop();
    if (!queue.includes(newNode )) {
      queue.push(newNode );
      stack= [...stack, ...graph[newNode]];
    }
  }
  return queue;
};

MJinH avatar Oct 19 '22 14:10 MJinH

Code for DFS: class Graph_Implementation { constructor(v) { this.V = v; this.adj = new Array(v); for(let i = 0; i < v; i++) this.adj[i] = []; } addedges(v, w) { this.adj[v].push(w); }

DFSUtil(v, visited)
{
    visited[v] = true;
    document.write(v + " ");
    for(let i of this.adj[v].values())
    {
        let n = i
        if (!visited[n])
            this.DFSUtil(n, visited);
    }
}
DFS(v)
{
    let visited = new Array(this.V);
    for(let i = 0; i < this.V; i++)
        visited[i] = false;
    this.DFSUtil(v, visited);
}

}

g = new Graph_Implementation(4);

g.addedges(0, 1); g.addedges(0, 2); g.addedges(1, 2); g.addedges(2, 0); g.addedges(2, 3); g.addedges(3, 3);

document.write("Following is Depth First Traversal " + " "); g.DFS(2);

Output: image

BFS Code: class Graph_Implmentation { constructor(v) { this.V = v; this.adj = new Array(v); for(let i = 0; i < v; i++) this.adj[i] = []; } addedges(v, w) { this.adj[v].push(w); } BFS(s) { let visited = new Array(this.V); for(let i = 0; i < this.V; i++) visited[i] = false; let queue=[]; visited[s]=true; queue.push(s); while(queue.length>0) { s = queue[0]; document.write(s+" "); queue.shift(); this.adj[s].forEach((adjacent,i) => { if(!visited[adjacent]) { visited[adjacent]=true; queue.push(adjacent); } }); } } } g = new Graph_Implmentation(11); g.addedges(1,2); g.addedges(1,4); g.addedges(2,3); g.addedges(2,6); g.addedges(3,5); g.addedges(3,7); g.addedges(4,6); g.addedges(5,2); g.addedges(5,6); g.addedges(6,1); g.addedges(7,5);

console.log("Following is Breadth First Traversal " + " ");

g.BFS(1);

Output: image image

Nimra-1234 avatar Dec 11 '22 09:12 Nimra-1234

@aked21 I guess this will help you. If it is so then you can close this issue.

https://github.com/apache/age-viewer/issues/44#issuecomment-1345502362

Nimra-1234 avatar Dec 24 '22 12:12 Nimra-1234

Thank you @Nimra-1234 @MJinH

shinhanbyeol avatar Dec 29 '22 08:12 shinhanbyeol