【发布时间】:2013-01-22 22:40:10
【问题描述】:
我正在开发一个 Boggle 游戏,有人告诉我搜索单词的最佳方法是使用递归。我正在尝试使用 searchWord 方法来搜索单词。如果找到第一个字母,该方法会调用自身并删除第一个字母。当长度 == 0(找到单词)或 false(未找到字母)时,该方法返回 true。问题有时令人难以置信,一个“骰子”周围有多次相同的字母......为了解决这个问题,我需要计算那个字母,如果它不止一次,它应该搜索那个字母的下一个出现(搜索同一个词,不丢首字母)。我需要一种方法来记住该字母和多个字母所围绕的字母的索引,以便在找不到字母时可以使用它来检查是否还有其他可能性。由于它是一种递归方法,我不知道如何将它们放入变量中,因为只要方法调用自身,它们就会被更改......
希望大家帮忙!方法如下:
public boolean searchWord(String word, int i, int j) {
boolean res;
if (word.length() == 0) {
res = true;
} else {
String theWord = word.toUpperCase();
int[] indexes = searchLetter(Character.toString(theWord.charAt(0)), i, j);
if (indexes[0] > -1) {
res = searchWord(theWord.substring(1), indexes[0], indexes[1]);
} else if(countLetter(Character.toString(/*The value that has to be memorized*/), /*index 1 that has been memorized*/, /*index 2 that has been memorized*/) > 1) {
res = searchWord(theWord, i, j);
} else {
res = false;
}
}
return res;
}
注意:是的,我使用的是奇怪的字符串,因为字符可能是更好的选择,但我可以稍后更改。
【问题讨论】:
标签: java arrays recursion boggle