I have written a recursive implementation for finding some specific path given some n*n matrix using this psuedocode I found on stackoverflow . I have constructed two arrays:
- path weight array that holds the edge value going from one vertex in our graph to another (cell matrix to neighboring cells in matrix)
- an adjacency array for each index in our path weight array
For some reason however my when my recursive function returns it doesn't return to the immediate caller?
My implementation:
// find paths of specific length from our starting cell 1,1
// when a path is found print it
// otherwise return?
function findPaths(adjMatrix, pathW_array, path, pathWeight, x, y, idx, curpath_idx){
// set curpath to the current path (an array with storing path weight values)
var curpath = path;
// tempArray with store pathW_array (set cell value to -1 if value has been added to curpath)
var tempArray = pathW_array;
// curValue retruns sum value of our curpath
if ( (curValue(curpath) == pathWeight) && (Object.keys(curpath).length !=1)){
for(i = 0; i < Object.keys(curpath).length; i++){
console.log(curpath[i]);
}
return;
}if(tempArray[x][y] == -1){
return;
}if(curValue(curpath) > pathWeight){
return;
}
// Did not return, add current cell value to curpath array
curpath[curpath_idx] = tempArray[x][y];
curpath_idx = curpath_idx + 1;
// set current cell value in tempArray to -1 because we've added it to current path (do not want to add same cell value multiple times)
tempArray[x][y] = -1;
// iterate until i = pathWeight -1
for(var i = 0; i < pathWeight; i++){
if(adjMatrix[idx][i] != -1){
// get pathW_array indices for next neighbor cell of current element
arrayIndices = neighbor_value(adjMatrix, tempArray, idx);
x = arrayIndices[0];
y = arrayIndices[1];
adjMatrix[idx][i] = -1;
idx = adjMatrix_idx(x,y);
// findpaths from the next cell in the matrix
findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx);
curpath.pop();
curpath_idx = curpath -1;
}
}
}