1

我已經寫了一個遞歸實現,以找到某些特定的路徑給出了一些n * n矩陣,使用我在stackoverflow上找到的這個psuedocode。我已經構建兩個數組:遞歸函數不返回到直接調用者

  1. 路徑權重陣列保持該邊緣值在我們的圖形從一個頂點到另一個(細胞基質對相鄰小區中的矩陣)
  2. 鄰接陣列,用於在我們路徑中的每個索引重量陣列

因爲某些原因,但是當我的遞歸函數返回它不會返回到直接調用者?

我的實現:

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

回答

0

更改以下行:

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

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

不理解複雜的其餘部分的功能,這 '應該' 迴歸遞歸返回值調用堆棧。