I am trying to understand recursion and so was trying to write a recursive function for the minesweeper game. My program has no game interface as it is just for the purpose of understanding.
Here is my understanding:
I have a grid of given size which will be filled with numbers. For simplicity I have assumed that the 0 will represent mine and an empty cell in grid will be represented by digit 9. Here is my grid:
0 1 9 9 9
1 1 9 9 9
9 9 9 9 9
9 9 9 1 1
9 9 9 1 0
Here is my recursive algorithm. I think I have put in the right boundary conditions but seems like the algorithm that goes into infinite recursion:
Base case:
IF the grid coordinates are less than 0 i.e x<0 OR y<0 OR x> grid.length-1 OR y > grid.length-1
return
ELSE
If the grid shows a number other than 0 or 9 , display the number i.e. grid[x][y]!=0 && grid[x][y]!=9
else If grid shows 0 that means it is a mine, display Game over
else
Recursive cases for all surrounding 8 cells as all surrounding cells are safe to open
Here is some code to show what I have listed in the algorithm:
public static void playGame(int[][]grid, int x, int y){
if(x > grid.length-1 || x <0 || y > grid.length-1 || y<0){
return;
}else{
if(grid[x][y] !=0 && grid[x][y]!=9){
//means this is a valid number to display to user
System.out.println("opening cell:"+x+","+y+" "+grid[x][y]);
}else if(grid[x][y] == 0){
System.out.println("Game over!");
//might want to show all mine locations
}else{
//all 8 cells are safe to open
playGame(grid,x-1,y-1); //left
playGame(grid,x,y-1); //up
playGame(grid,x,y+1);//down
playGame(grid,x+1,y);//diagonal
playGame(grid,x-1,y); //diagonal
playGame(grid,x+1,y-1);//diagonal
playGame(grid,x+1,y+1);//right
playGame(grid,x-1,y+1);//diagonal
}
}
}
I passed the cell as 2,2 and it gives me java.lang.StackOverflowError. Can someone please guide me here. Is there a problem with my understanding on the algorithm or recursion or there is some bug that I have may have introduced. I am unable to spot the problem.