Optimising minesweeper method
i have been trying to make a minesweeper applet to put on my website.
but when it comes to "rolling back" the squares when the user clicks on a square that has no surrounding mines the applet is really slow. I know this probably isn't the best way to code it because I've seen other minesweeper applets that run A LOT faster than mine, but it was the only way I could think to make it work. Any help would be appreciated.
/**
* Reveals surrounding squares when a blank area is clicked on
*/
publicvoid blankReveal(MineButton theButton)
{
ArrayList blankList =new ArrayList();
blankList.add(theButton);
while(blankList.size()>0)
{
MineButton middleSquare = (MineButton) blankList.get(0);
squareReveal(middleSquare);
int col = middleSquare.getCol();
int row = middleSquare.getRow();
for(int x = -1 ; x < 2 ; x++)
for(int y = -1; y < 2; y++)
{
try
{
MineButton currentSquare = mines[col+x][row+y];
if(currentSquare.isRaised())
{
if(currentSquare.getSurroundingMines()==0 & !currentSquare.isFlagged())
{blankList.add(currentSquare);}
else squareReveal(currentSquare);
}
}
catch (ArrayIndexOutOfBoundsException e){}
}
blankList.remove(0);
}
}
[2243 byte] By [
GemmaPa] at [2007-9-28 15:00:41]

Try avoiding visiting squares multiple times... Also, LinkedList is far better for this type of usage than ArrayList.
/**
* Reveals surrounding squares when a blank area is clicked on
*/
public void blankReveal(MineButton theButton)
{
List blankList = new LinkedList();
blankList.add(theButton);
Set visited = new HashSet();
visited.add(theButton);
while(blankList.size()>0)
{
MineButton middleSquare = (MineButton) blankList.get(0);
squareReveal(middleSquare);
int col = middleSquare.getCol();
int row = middleSquare.getRow();
for(int x = -1 ; x < 2 ; x++)
for(int y = -1; y < 2; y++)
{
try
{
// YATArchivist wonders how sure you are that the next line
// never causes ArrayIndexOutOfBoundsException...
MineButton currentSquare = mines[col+x][row+y];
if(currentSquare.isRaised() && !visited.contains(currentSquare))
{
if(currentSquare.getSurroundingMines()==0 & !currentSquare.isFlagged())
{
blankList.add(currentSquare);
visited.add(currentSquare);
}
else squareReveal(currentSquare);
}
}
catch (ArrayIndexOutOfBoundsException e){}
}
blankList.remove(0);
}
}
I'm assuming calling squareReveal causes further calls to isRaised to return false. I'm also assuming getSurroundingMines() returns a cached value and doesn't check all adjacent squares.