Java 查找boggle板中是否存在单词的调试递归方法
我正在尝试实现一个boggle解算器 我的基本想法是创建一个方法来检查单词是否在黑板上。然后通过删除以char开头的单词来修剪我的字典,然后将该方法应用于字典集中的每个单词,以获得解决方案集 我不完全确定这个解决方案有多有效。。我很确定它只在O(n)(与字典集的大小成比例)上运行,这在更大的板(5x5-7x7)上会更好 我当前的方法(如果我可以修复访问的工作方式,则该方法应该有效): 另外,我刚刚意识到我的“FindFirstile”方法只会在以该字母开头的最后一个磁贴上查找单词。。。因此,如果在黑板上多次出现该字母,它可能不会浏览所有字母 这也是我的平铺对象的构造函数:Java 查找boggle板中是否存在单词的调试递归方法,java,debugging,recursion,depth-first-search,boggle,Java,Debugging,Recursion,Depth First Search,Boggle,我正在尝试实现一个boggle解算器 我的基本想法是创建一个方法来检查单词是否在黑板上。然后通过删除以char开头的单词来修剪我的字典,然后将该方法应用于字典集中的每个单词,以获得解决方案集 我不完全确定这个解决方案有多有效。。我很确定它只在O(n)(与字典集的大小成比例)上运行,这在更大的板(5x5-7x7)上会更好 我当前的方法(如果我可以修复访问的工作方式,则该方法应该有效): 另外,我刚刚意识到我的“FindFirstile”方法只会在以该字母开头的最后一个磁贴上查找单词。。。因此,如果
public Tile (char letter, int place){ // NOTE: the char MUST BE capital
this.letter = letter;
this.place = place;
try {
img = ImageIO.read(new File("tile"+letter+".png"));
} catch (IOException e) {
}
我引用的Tile数组(tiles)也是按顺序排列的所有Tile的数组
所以基本上在我的董事会上:
tiles[0] tiles[1] tiles[2] tiles[3]
tiles[4] tiles[5] tiles[6] tiles[7]
tiles[8] tiles[9] tiles[10] tiles[11]
tiles[12] tiles[13] tiles[14] tiles[15]
而“位置”(来自Tile构造函数)只是
我已经检查了我的getNeights()和getChar()以及getPlace()方法,它们都按预期工作。以防有人怀疑(可能不是,lol) 以下是修订后的(和有效的)代码:
public boolean findwordboard(字符串字、平铺、整数深度、哈希集){
if(depth==word.length())返回true;//基本大小写-中断递归(板上)
否则{
word=word.toUpperCase();
如果(tile==null)返回false;
HashSet neights=map.get(tile.getPlace());
for(int n:邻居){
if(depth>=word.length())返回true;
if((tiles[n-1].getChar()==word.charAt(深度))&&(!visted.contains(n))){
添加(n);
System.out.println(“在“+n”处找到“+tile.getChar()+”);
返回findWordOnBoard(字,分片[n-1],深度+1,已访问);
}
}
}
return false;//只有在找不到新词的情况下才会到达这里
}
问题只是返回递归调用,而不是直接进行调用,因为当它向后通过递归时,基本大小写调用会中断(depth==word.length())
当深度回到1时不再为真。不要继续删除并重新发布同一个问题。如果你的问题没有得到足够的关注,当你获得足够的声誉时。由于boggle board很可能比“普通”词典包含的单词少几个数量级,我会从boggle board开始,尝试从词典中删除不可能的单词。如果你从“S”开始,你就大大减少了搜索空间,使得寻找可能匹配的搜索速度更快。
public Tile (char letter, int place){ // NOTE: the char MUST BE capital
this.letter = letter;
this.place = place;
try {
img = ImageIO.read(new File("tile"+letter+".png"));
} catch (IOException e) {
}
tiles[0] tiles[1] tiles[2] tiles[3]
tiles[4] tiles[5] tiles[6] tiles[7]
tiles[8] tiles[9] tiles[10] tiles[11]
tiles[12] tiles[13] tiles[14] tiles[15]
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
public boolean findWordOnBoard(String word, Tile tile, int depth, HashSet<Integer> visited) {
if (depth == word.length()) return true; // base case - breaks recursion (on board)
else {
word = word.toUpperCase();
if (tile == null) return false;
HashSet<Integer> neighbors = map.get(tile.getPlace());
for (int n : neighbors) {
if (depth >= word.length()) return true;
if ((tiles[n-1].getChar() == word.charAt(depth)) && (!visited.contains(n))) {
visited.add(n);
System.out.println("found " + tile.getChar() + " at " + n);
return findWordOnBoard(word, tiles[n-1], depth+1, visited);
}
}
}
return false; //will only get here if it doesn't find a new word
}