FloodFill - Minesweeper, Explanation needed

北战南征 提交于 2019-12-24 15:01:59

问题


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);

回答1:


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)




回答2:


I guess u r mainly asking about floodfill. Actually it is a simple and common recursive algorithm. It can solve whatever your data structure is 1D or 2D. For 2D version, @RMoeller has given the answer. For your previous 1D declaration, it is also similar like this:

void floodFill( int pos ) {
   if ( btn( pos ) isFillable ) {
       fillBtn(pos);
       floodFill( pos+1 );
       floodFill( pos-1 );
       floodFill( pos+10 );
       floodFill( pos-10 );
   } else {
       return;
   }
}

One thing u should remember is, floodfill, and almost all recursive algorithm, needs to check the boundary. Otherwise u may get into an infinite loop or get a wrong result. In above example(1D version), u should check whether: pos >= 1 && pos <= 100 Similar to 2D version which is to check: x >= 1 && x <= 10 && y>=1 && y <=10

Hope this helps.



来源:https://stackoverflow.com/questions/14076090/floodfill-minesweeper-explanation-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!