【问题标题】:My Boggle program won't find all the valid words - Java我的 Boggle 程序找不到所有有效单词 - Java
【发布时间】:2012-10-16 19:19:02
【问题描述】:

所以我正在用 Java 开发一个 Boggle 程序,但我无法让它找到每一个可能的单词。

它几乎可以找到所有这些,但对于我的生活,我无法弄清楚为什么它不能全部找到。

private void findWords( TreeSet<String> foundWords, String word, Tile t ){
    int i=t.getRow();
    int j=t.getCol();

    //Make sure the tile isn't visited
    if(visited[i][j]) return;

    //Set the current tile to visited
    visited[i][j]=true;

    //Decide what the current word is
    if(t.getLetter().equalsIgnoreCase("q")) word=word+"qu";
    else word=word+t.getLetter();

    //If the string is a word
    if(Boggle.dictionary.search(word)==1){
        //If the word length is greater than or equal to the prefix length
        if(word.length()>=Dictionary.prefixLength){
            //If the word has not already been found
            if(!foundWords.contains(word)){
                //Add the word to the found list
                foundWords.add(word);   
            }
        }
    }

    //Recurse through all neighbor tiles
    for(int curRow=0; curRow<=nRows; curRow++){
        for(int curCol=0; curCol<=nCols; curCol++){
            //Make sure it is not out of bounds
            if((i+curRow<nRows)&&(j+curCol<nCols)){
                findWords(foundWords, word, board[i + curRow][j + curCol]); 
                findWords(foundWords, word, board[i - curRow][j - curCol]); 

                findWords(foundWords, word, board[i + curRow][curCol]); 
                findWords(foundWords, word, board[i - curRow][curCol]); 

                findWords(foundWords, word, board[curRow][j + curCol]); 
                findWords(foundWords, word, board[curRow][j - curCol]); 

                findWords(foundWords, word, board[i + curRow][j - curCol]);
                findWords(foundWords, word, board[i - curRow][j + curCol]);
            }
        }
    }

    //Reset the tile to be not visited
    visited[i][j] = false;
}

这是有问题的方法;它递归地在 Boggle 板上找到单词。

有人知道为什么它只能找到大约 75% 的单词吗?

如果需要,我可以附加更多代码。

【问题讨论】:

  • 什么是nRows?我认为,在这种情况下,单元测试是你的朋友。
  • nRows 是 Boggle.java 传入的行数,我没有包含在其中。如果它更清楚,我可以发布整个程序,但它是 5 个类文件和一个字典文件。
  • 它是否适用于矩阵 [[A,N],[T,I]] -- 生成“AN”“AT”“IT”“IN”“ANT”“TAN”“TIN ” 和“ANTI”(也许还有“TI”)?
  • 您的编辑极大地改变了您的代码。

标签: java recursion boggle


【解决方案1】:

我建议编写一些测试用例 - 我总是发现这样做要么立即发现问题,要么至少允许您使用调试器单步调试代码,并找出实际与您的预期不同的地方。

编辑:另外,你的两个 for 循环看起来很奇怪。您不应该在每个方向上查看 -1,0 和 1 的偏移量(并折扣 0,0),而不是 0 -> nRows?看来你只看一个方向。

【讨论】:

  • 我有几个测试用例;这只是我的程序的一小部分。我添加了几个递归调用 findWords 的案例,我想我得到了每个案例。它确实找到了更多的词,但仍然不是全部。我只是不认为将 5 个类的代码加上一个字典文件放在一篇文章中是个好主意。
猜你喜欢
  • 2018-12-20
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多