我正在尝试解决一个令人难以置信的单词检查器问题,我快到了,但我需要一些逻辑帮助。Boggle 单词检查器需要一个二维数组和一个字符串,我想确定该字符串是否是返回 true 或 false 的有效 boggle 单词。因此,有效的猜测是可以通过连接相邻单元格(水平、垂直或对角线)而不重新使用任何先前使用的单元格来形成的字符串。
例如 EAR 是正确的,但 EARS 不是。
据我所知,它似乎可以正常工作,直到它到达最后一个字母,然后我遇到了正确返回 T/F 的问题。我尝试使用 if 语句来停止递归调用,但它似乎不起作用。任何关于如何解决的建议都会很棒!
final private static char[][] board = {
{'E','A','R','A'},
{'N','L','E','C'},
{'I','A','I','S'},
{'B','Y','O','R'}
}
public class Boggle {
char[][] board;
String word;
public Boggle(final char[][] board, final String word) {
this.board = board;
this.word = word;
}
public boolean checkit() {
//make string array
//iterated through board
//if word[0] == board value
//check -> see if value above beloow left right is a match to word[1]
System.out.println("word: "+word);
char[] charArr = word.toCharArray();
int index = 0;
boolean valid = false;
for(int row=0; row< board.length; row++) {
for(int col=0; col<board[0].length; col++) {
if(board[row][col] == charArr[index]) {
return check(board, charArr, row, col, index);
}
}
}
return valid;
}
public boolean check(char[][] board, char[] charArr, int row, int col, int index) {
index++;
//while index< charArr.length, keep searching for matches
System.out.println("index: "+index + " chararr.length: "+charArr.length);
if(index >= charArr.length) return true;
else if(index < charArr.length) {
System.out.println("here");
//check up
if(row-1 >= 0) {
if(board[row-1][col] == charArr[index]) {
check(board, charArr, row-1, col, index);
}
}
//check up/right (diagonal)
else if((row-1 >= 0) && (col+1 < board[0].length)) {
if(board[row-1][col+1] == charArr[index]) {
check(board, charArr, row-1, col+1, index);
}
}
//check right
else if(col+1 < board[0].length) {
if(board[row][col+1] == charArr[index]) {
System.out.println("right");
check(board, charArr, row, col+1, index);
}
}
//check right/down (diagonal)
else if((col+1 < board[0].length) && (row+1 < board.length)) {
if(board[row+1][col+1] == charArr[index]) {
check(board, charArr, row+1, col+1, index);
}
}
//check down
else if(row+1 < board.length) {
if(board[row+1][col] == charArr[index]) {
check(board, charArr, row+1, col, index);
}
}
//check down/left (diagonal)
else if((col-1 >= 0) && (row+1 < board.length)) {
if(board[row+1][col-1] == charArr[index]) {
check(board, charArr, row+1, col-1, index);
}
}
//check left
else if(col-1 >= 0) {
if(board[row][col-1] == charArr[index]) {
check(board, charArr, row, col-1, index);
}
}
//check left/up (diagonal)
else if((col-1 >= 0) && (row-1 >= 0)) {
if(board[row-1][col-1] == charArr[index]) {
check(board, charArr, row-1, col-1, index);
}
}
//no match
System.out.println("false section");
return false;
} //end while
return false;
}
}