0

我必须为类似 Boggle 的游戏编写一个程序,我现在让它检查当前字母下方的每个字母,看看它们是否会造字。所以对于像这样的董事会:

W O Y R
F U M F
H T R V
I G S W

它会找到的唯一词是从上到下的“OUT”。当它找到一个单词的一部分时,它将该字母放入一个字符串并将其设置为 null,因此它不会在同一个单词中使用两次字母(完整的算法必须能够在多个方向上搜索)。我使用堆栈来跟踪我使用过的字母的坐标,以便我可以回溯,每次弹出堆栈时,我都会取出字符串的最后一个字母并将其放回板的原始位置。但问题是,如果多个字母被删除,它会将它们都放在同一个索引中,覆盖前一个。因此,在“OUT”的情况下,在替换三个字母后,电路板最终看起来像这样:

W null Y R
F null M F
H  O   R V
I  G   S W

我已经浏览了我的代码并尝试重写它两次,但它总是这样做。您对为什么会发生这种情况有任何见解吗?

private void checkNeighbors(LetterCoor center){
    String check = out;
    while (!path.empty()){
        if(center.getDirec()==0){//If the direction to check is down
            System.out.println("Bottom");
            if((center.getRow())+1<sideLength && board[(center.getRow())+1][center.getCol()]!=null){//makes sure the space below is !null and !out of bounds
                check+=board[center.getRow()+1][center.getCol()];
                System.out.println("Checking " + check);
                if(isValidWord(check)){//checks if string is part of the lexicon
                    center.nextNeighbor();
                    board[center.getRow()+1][center.getCol()]=null;
                    center = new LetterCoor(center.getRow()+1, center.getCol(), 0);
                    System.out.println("push " + check.substring(check.length()-1));
                    path.push(center);
                    out=check;

                }
                else{
                    center=(LetterCoor) path.pop();
                    center.nextNeighbor();
                    path.push(center);
                }
            }//end of null if
            else{
                System.out.println("Null or end of board");
                center=(LetterCoor) path.pop();
                center.nextNeighbor();
                path.push(center);
            }
        }//end of direc 0 if
        else{
            System.out.println("pop " + out.substring(out.length()-1,out.length()));
            center=(LetterCoor) path.pop();
            center.nextNeighbor();
            board[center.getRow()][center.getCol()]=out.substring(out.length()-1,out.length());
            out=out.substring(0,out.length()-1);
            if (center.getDirec()<1){
                path.push(center);
            }
        }
        System.out.println("Current string is " + out);
    }//end of while loop
}

如果您需要澄清我的代码,请告诉我。

此外,作为澄清,LeterCoor 对象存储三个整数。第一个是字母的行索引,第二个是列索引,第三个表示它正在搜索的方向(0=向下,1=右下,2=右等)

4

1 回答 1

0

我最终自己遇到了解决方案。问题出在我的 LetterCoor 对象上。Eclipse 需要将变量设置为静态,因为我在单独的文件中拥有对象类,因此当我更新一个 LetterCoor 对象中的坐标数据时,它会将每个 LetterCoor 对象的数据设置为该坐标。我通过将对象类移动到与此类相同的文件中并从变量中删除静态声明来解决此问题。

于 2014-08-05T16:38:32.690 回答