请解释为什么我的代码导致堆栈溢出错误

时间:2019-10-21 01:01:49

标签: java recursion stack-overflow

代码如下:

margin

在更改y值的if语句中,引起堆栈溢出错误,但是在更改x值的部分中没有错误。我想知道为什么会这样。如果两者都错了,我将改变整个事情,但是仅在第二和第四次if语句中表明Stack Overflow错误是由递归调用引起的。第一个和第三个if语句没有问题,我完全不知道它们有什么不同。

1 个答案:

答案 0 :(得分:1)

这是因为当您的代码从0,0移到1,0时,它会在满足第一个0,0条件时再次检查if


public static int[][] visitedNodes;

public static void main(String args[]){
  // when you call the recursive method, also initiate the visitedNodes
   visitedNodes = new int[totalX][totalY];
   for(int i = 0; i < totalX; i++)
     for(int j = 0; j < totalY; i++)
        visitedNodes[i][j] = 0;
   maxPathLengthHelper(myPathList,0,0);
}

public static int maxPathLengthHelper(int[][] paths, int x, int y){
    int maxLength = 0;
    visitedNodes[x][y] = 1;
    if(x > 0 && visitedNodes[x-1][y] == 0 && paths[x-1][y] == 1){
        int currentLength = 1 + maxPathLengthHelper(paths,x-1,y);
        if(currentLength > maxLength){
            maxLength = currentLength;
        }
    }
    if(y > 0 && visitedNodes[x][y-1] == 0  && paths[x][y-1] == 1){
        int currentLength = 1 + maxPathLengthHelper(paths,x,y-1);
        if(currentLength > maxLength){
            maxLength = currentLength;
        }
    }
    if(x < paths.length - 1 && visitedNodes[x+1][y] == 0  && paths[x+1][y] == 1){
        int currentLength = 1 + maxPathLengthHelper(paths,x+1,y);
        if(currentLength > maxLength){
            maxLength = currentLength;
        }
    }
    if(y < paths[0].length - 1 && visitedNodes[x][y+1] == 0  && paths[x][y+1] == 1){
        int currentLength = 1 + maxPathLengthHelper(paths,x,y+1);
        if(currentLength > maxLength){
            maxLength = currentLength;
        }
    }
    return maxLength;
}