Search code examples
javastack-overflow

Why this code throw a StackOverflowError


I want to do a kind of path finding. Then I used a FIFO queue to assign a distance number from a cell and do it recursivly for their neighbors if they have a default number.

On small space it work fine but I don't understand why it throw a StackOverflowError when I try on higher space (100x100).

My Position class is just a tuple of (X,Y).

Someone have an idea of what is wrong? I was thinking that my LinkedList will just browse the whole space and stop it.

public class Main {

    public static int[][] cells; //[Y][X]
    public static LinkedList<Position> modifiedCells = new LinkedList<Position>();


    public static void assignNumber(int posX, int posY) {
        int currentNumber = cells[posX][posY]+1;

        int globalX, globalY;
        for (int x = posX-1; x <= posX+1; x++) {
            for (int y = posY-1; y <= posY+1; y++) {
                if(y>=0 && y< cells[0].length && x>=0 && x<cells.length && cells[x][y] == 0)   { 
                    //out of border or still 0.
                    cells[x][y] = currentNumber;
                    modifiedCells.addLast(new Position(x,y));
                }
            }
        }

        if(modifiedCells.size() > 0){ 
            //take the next cell on list and assign number on neighbors
            Position pos = modifiedCells.removeFirst();
            assignNumber(pos.getX(),pos.getY());
        }
    }

    public static void main(String[] args) {

        cells = new int[100][100];

        for (int x = 0; x < 100; x++) {
            for (int y = 0; y < 100; y++) {
                cells[x][y] = 0;
            }
        }
        assignNumber(50,50);
    }
}

Solution

  • The default maximum stack (ie recursion) depth is 1000. 100 x 100 would result in a depth of 10000.

    Some algorithms (such as this one) do not scale well as the problem space grows.

    To make it work, you could try setting a bigger stack size:

    java -Xss1G com.mypackage.Main