Search code examples
javaalgorithmflood-fill

FloodFill - Minesweeper, Explanation needed


I'm trying to make a Minesweeper-like game in Java and I've got most of it to work. Something I need help with is FloodFill - http://en.wikipedia.org/wiki/Flood_fill.

Can someone explain how it works? I've looked online but I don't really understand the explanation so I thought it would be easier to ask here.

In my Minesweeper I have:

JButton[] btn = new JButton[100]//buttons being clicked and displaying the values/bombs
int[] mines = new int[100];//int array holding the values for each button.

The grid is a 10x10 grid so say the button you clicked was btn[14],

btn[4]  // north of btn[14](14-10)
btn[24] // south of btn[14](14+10)
btn[13] //  west of btn[14](14-1)
btn[15] //  east of btn[14](14+1)

So back to the question, could someone explain it to me?

EDIT: I changed my code to be 2D so instead of the above one it is now

btn[1][4]//row one, column 4

When the button is clicked, i want it to check a variable called mines[][] which has the values and if the value is equal to 0(around the initial clicked) it changes the BG

btn[x][y].setBackground(Color.GRAY);

Solution

  • Its a recursive algorithm. You start at some start position in a 2D Grid [x,y], then look in all directions and fill them if you can. If (x,y) can't be filled, return.

    void floodFill( int x, int y ) {
       if ( btn( x, y ) isFillable ) {
           fillBtn(x,y);
           floodFill( x+1, y );
           floodFill( x-1, y );
           floodFill( x, y-1 );
           floodFill( x, y+1 );
       } else {
           return;
       }
    }
    

    (ommited check for boundaries of grid)