用JAVA编了一个扫雷的程序。在点击按钮后,如果旁边8个有不是雷就显示,用了一个递归算法,里面有几个if语句,但就只是执行了一个if语句的递归???不知道为什么?下面是使用递归算法的函数:
public void showCount(ExtendButton b) //踩不到雷,显示相关信息
{ b.setText(String.valueOf(b.getCount())); //显示旁边雷数
int i=b.getColumn(),
j=b.getRow();
/* 以递归的方式对旁边不是雷的区进行同样的操作 */
if((j-1)>=0&&(!button[i][j-1].getStatus())) //若其左不为空
{
showCount(button[i][j-1]);
}
if((i-1)>=0&&(!button[i-1][j].getStatus())) //若其上不为空
{
showCount(button[i-1][j]);
} if((i+1)<number&&(!button[i+1][j].getStatus())) //若其下不为空
{
showCount(button[i+1][j]);
}
if((j+1)<number&&(!button[i][j+1].getStatus())) //若其右不为空
{
showCount(button[i][j+1]);
}
}
public void showCount(ExtendButton b) //踩不到雷,显示相关信息
{ b.setText(String.valueOf(b.getCount())); //显示旁边雷数
int i=b.getColumn(),
j=b.getRow();
/* 以递归的方式对旁边不是雷的区进行同样的操作 */
if((j-1)>=0&&(!button[i][j-1].getStatus())) //若其左不为空
{
showCount(button[i][j-1]);
}
if((i-1)>=0&&(!button[i-1][j].getStatus())) //若其上不为空
{
showCount(button[i-1][j]);
} if((i+1)<number&&(!button[i+1][j].getStatus())) //若其下不为空
{
showCount(button[i+1][j]);
}
if((j+1)<number&&(!button[i][j+1].getStatus())) //若其右不为空
{
showCount(button[i][j+1]);
}
}
这是我扩展的一个JButton类
package clearbomb;
import javax.swing.*;
public class ExtendButton extends JButton
{
boolean isbomb=false;
int count=0;
int column,row;
public ExtendButton(int i,int j)
{
column=i;
row=j;
} public void setStatus(boolean b)
{
isbomb=b;
}
public void incCount()
{
count++;
}
public boolean getStatus()
{
return isbomb;
}
public int getCount()
{
return count;
}
public int getColumn()
{
return column;
}
public int getRow()
{
return row;
}
}