Search code examples
javaarraysstack-overflowflood-fillminesweeper

Simple flood fill method causes StackOverFlow error


My flood fill method:

public void fillNeighbours(int x, int y) {
    for(int i = -1; i < 2; i++) {
        for(int j = -1; j < 2; j++) {
            try {
                visible[x+i][y+j] = true;

                if(num[x+i][y+j] == 0) {
                    fillNeighbours(x+i, y+j);
                }
            } catch (ArrayIndexOutOfBoundsException ignored) {}
        }
    }
}

That catch (ArrayIndexOutOfBoundsException ignored) {} is there for avoiding x and/or y position from going outside of the array. Array size is 30 by 30. I'm making minesweeper like game. So you may know why I need this method and how it should work. If u don't know what minesweeper is then here is quick video about that game: Introduction to minesweeper


Solution

  • The code revisits fields which are set to visible already.

    Try something like

    if(!visible[x+i][y+j]){
      visible[x+i][y+j] = true;
      if(num[x+i][y+j] == 0) {
        fillNeighbours(x+i, y+j);
      }
    }