【发布时间】:2016-07-15 15:30:49
【问题描述】:
我正在开发 Boggle 游戏,我正在创建一个名为 findWord 的方法,如果可以在“网格”中找到“单词”,则该方法返回 true。返回 false 否则私有成员变量 grid 有字母 grid。但是,当我运行我的主要方法时,它会一直打印“未找到”,我无法弄清楚我在哪里犯了错误!这是我的代码
public class BoggleGame_old {
LetterGrid grid;
private char[][]board;
boolean[][] visited;
public BoggleGame_old(LetterGrid g)
{
grid = g;
}
public boolean findWord(String word) {
for(int row=0;row<this.board.length;row++){
for(int col=0;col<this.board.length;col++){
if(this.find(word, row, col)){
return true;
}
}
}
return false;
}
//helping function
private boolean find(String word, int row, int col){
if(word.equals(""))
{
return true;
}
else if(row<0||row>=this.board.length||
col<0||col>=this.board.length||
this.board[row][col] != word.charAt(0))
{
return false;
}
else{
char c=this.board[row][col];
this.board[row][col]='*';
String curr=word.substring(1,word.length());
boolean res=this.find(curr, row-1, col-1)||
this.find(curr, row-1, col)||
this.find(curr, row-1, col+1)||
this.find(curr, row, col-1)||
this.find(curr, row, col+1)||
this.find(curr, row+1, col-1)||
this.find(curr, row+1, col)||
this.find(curr, row+1, col);
this.board[row][col]=c;
return res;
}
}
【问题讨论】:
-
你的内部for循环中的条件应该是
col < this.board[row].length;(你可以省略this。它是多余的,因为没有歧义)。 -
第二个 if、second 或 help 函数中的条件相同(只允许例外,但不是好的做法:如果板子保证有正方形大小)。