Explore Library
Code QuizAdvanced

DFS Stack Behavior

Find why this depth-first search actually explores breadth-first.

Codejavascript
function dfs(graph, start, goal) {
  const stack = [start];
  const visited = new Set();
  while (stack.length > 0) {
    const node = stack.shift();
    if (node === goal) return true;
    if (!visited.has(node)) {
      visited.add(node);
      for (const next of graph[node]) stack.push(next);
    }
  }
  return false;
}

This function claims to do DFS but expands nodes level by level. What is the bug?