简体   繁体   中英

why my code java.lang.StackOverflowError?

private void findRute(int x1, int y1, int x2, int y2, int counter)
    {
        try
        {
            if((x1 == x2) && (y1 == y2))
            {
                if(this.min > counter)
                {
                    this.min = counter;
                }
            }
            else
            {
                if(map[x1-1][y1] == 0)
                {
                    this.findRute(x1 - 1, y1, x2, y2, counter + 1);
                }
                if(map[x1+1][y1] == 0)
                {
                    this.findRute(x1 + 1, y1, x2, y2, counter + 1);
                }
                if(map[x1][y1 + 1] == 0)
                {
                    this.findRute(x1, y1 + 1, x2, y2, counter + 1);
                }
                if(map[x1][y1 - 1] == 0)
                {
                    this.findRute(x1, y1 - 1, x2, y2, counter + 1);
                }
            }
        }
        catch(IndexOutOfBoundsException z)
        {

        }
    }

Let's say the map consists entirely of zeroes, and you're in the top left corner. You're going to move one step to the right, then one step to the left, then one step to the right again, and so on.

You need to somehow mark the cells you've already visited, to prevent the infinite recursion.

Also, the catching of IndexOutOfBoundsException is not such a good idea:

  • firstly, I wouldn't consider it good style: if later on you were to add some code inside the try block that could also throw IndexOutOfBoundsException , your code would begin failing silently;
  • secondly, if the first check ( map[x1-1][y1] ) is out of bounds, you're going to skip of the remaining checks;

probably you try to access the -1 index or length+1

think what happen in the edge

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM