递归函数不返回直接调用者

时间:2017-03-02 10:40:42

标签: javascript algorithm recursion graph-algorithm path-finding

我已经编写了一个递归实现,用于使用我在stackoverflow上找到的psuedocode给出一些n * n矩阵来查找某个特定路径。我构建了两个数组:

  1. 路径权重数组,用于保存从图形中的一个顶点到另一个顶点的边缘值(单元格矩阵到矩阵中的相邻单元格)
  2. 路径权重数组中每个索引的邻接数组
  3. 出于某种原因,但是当我的递归函数返回时,它不会返回到直接调用者?

    我的实施:

            // 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;
                    }   
                }
            }
    

1 个答案:

答案 0 :(得分:0)

更改以下行:

findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx)

return findPaths(adjMatrix, tempArray, curpath, pathWeight, x, y, idx, curpath_idx)

如果不理解函数中其余的复杂性,那么'应该'将递归返回值返回到调用堆栈。