I am trying to do a graph traversal. Since all vertices are not connected. I need to initiate the traversal from every node. Nodes are in a 2d array. I am getting the input from a large text file and here is how I do it:
lr.on('end', function(){
//Callback called when file reading is complete
initialize(); //initialize stuff
startTraversal();
});
The startTraversal() method is defined as:
function startTraversal(){
for(i=0;i<x;i++){
for(j=0;j<y;j++){
console.log(i+', '+j);
traverse(i,j); //Call Traverse i,j every time once
}
}
}
traverse(i,j) is a recursive function. So I look at all possible paths from the node i,j and initiate traverse on them. A broad structure of the traverse() method is below:
function traverse(i,j){
var possible = getAdjacent(i,j); //getPossible Routes
if(possible.length == 0){
//do stuff
return; //Tried adding return statement here
}
else{
for(x=0;x<possible.length;x++){
if(!data[a][b].visited) //if node is not visited
traverse(a,b);
//Do further stuff when this ^ call returns, finding max etc
...
} //End of for
}
}
Now in the startTraversal() function call, the inner loop is executed only for the first value of i which I confirmed from the console.log. I am not able to understand why is the loop not getting executed further.
PS: When I manually put the nested loops outside any callbacks, the loops and traversal gets done as expected. However, I need to initiate the startTraversal() method only when the file is read completely. I guess it has something to do with the traverse() function not returning a value so that the loop is not continued. I tried adding a return in the base case of traverse method but to no success.
Any insights on this problem is deeply appreciated. Would want to know how to handle recursive calls in nested loops, atleast in javascript.
iandjas paramters to thetraversefunction. They will be passed by value right.getAdjacent()method doesn't have a callback. It just returns anarray.xinfor(x=0;x<possible.length;x++)is shared with all recursive function calls.