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 1 year 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