freeCodeCamp Challenge Guide: Depth-First Search

Depth-First Search

This is a stub. Help the community by making a suggestion of a hint and/or solution. We may use your suggestions to update the missing sections.


Problem Explanation

This summarizes what need to be done without just restating the challenge description and/or instructions. This is an optional section

Relevant Links


Hints

Hint 1

Hint goes here

Hint 2

Hint goes here


Solutions

Solution 1 (Click to Show/Hide)
function dfs(graph, root) {
  var stack = [];
  var tempV;
  var visited = [];
  var tempVNeighbors = [];
  stack.push(root);
  while (stack.length > 0) {
    tempV = stack.pop();
    if (visited.indexOf(tempV) == -1) {
      visited.push(tempV);
      tempVNeighbors = graph[tempV];
      for (var i = 0; i < tempVNeighbors.length; i++) {
        if (tempVNeighbors[i] == 1) {
          stack.push(i);
        }
      }
    }
  }
  return visited;
}

var exDFSGraph = [
  [0, 1, 0, 0],
  [1, 0, 1, 0],
  [0, 1, 0, 1],
  [0, 0, 1, 0]
];
console.log(dfs(exDFSGraph, 3));

Code Explanation

  • Code explanation goes here

Relevant Links

1 Like