Depth first search of graph

Hi,

I got this question from the interview prep section here I’m not sure why it does not pass the tests? I used recurrsion but it does not seem to pass the test. Here’s my code below :

function dfs(graph, root) {
 var nodesLen = {};

  for (var i = 0; i < graph.length; i++) {
    nodesLen[i] = Infinity;
  }
  nodesLen[root] = 0; 

function traverse(node)
{
    var curConnected = graph[node]; 
    var neighborIdx = []; 
    var idx = curConnected.indexOf(1);

    while (idx !== -1) {
    neighborIdx.push(idx); 
    idx = curConnected.indexOf(1, idx + 1);
    }
     for (var j = 0; j < neighborIdx.length; j++) {
     if (nodesLen[neighborIdx[j]] === Infinity) {
        nodesLen[neighborIdx[j]] = nodesLen[node] + 1;
        traverse(neighborIdx[j])
      } 
     }
    
  }

traverse(root)
return nodesLen

  }


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

Hello there,

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).


This is what your code returns:

{ '0': 0, '1': 1, '2': 2, '3': 3 }

This is what the instructions say:

Your function should output an array of all nodes reachable from root.

Can you see the problem?

Thanks i see it now. All sorted! :grinning: