我正在努力实现一种解决方案,以在5x5的随机字母板上找到所有单词。目前,它返回的只是几句话,而并非完整列表。我很确定我的问题存在于for循环的findWords方法中,但是我无法弄清楚如何使if语句继续在所有8个方向上遍历。

import java.io.File;
import java.util.*;
public class RandomWordGame {

    private static char[][] board = new char[5][5];
    private static Random r = new Random();
    private static ArrayList<String> dictionary = new ArrayList<String>();

    private static char[][] createBoard()
    {
        for (int i=0; i<board.length; i++)
        {
            for (int j=0; j<board.length; j++)
            {
                board[i][j] = (char) (r.nextInt(26) + 'a');
                System.out.print(board[i][j]);
            }
            System.out.println("");
        }
        System.out.println();
        return board;
    }
    public static ArrayList<String> solver(char[][] board)
    {
        if(board == null)
            System.out.println("Board cannot be empty");
        ArrayList<String> words = new ArrayList<String>();
        for(int i=0; i<board.length; i++)
        {
            for(int j=0; j<board[0].length; j++)
            {
                findWords(i, j, board[i][j] + "");
            }
        }
        return words;
    }
    public static void findWords(int i, int j, String currWord)
    {
        try
        {
            Scanner inputStream = new Scanner(new File("./dictionary.txt"));
            while(inputStream.hasNext())
            {
                dictionary.add(inputStream.nextLine());
            }
            inputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        for(i=0; i>=0 && i<board.length; i++)
        {
            for(j=0; j>=0; j++)
            {
                currWord += board[i][j];
                if(currWord.length()>5)
                    return;
                if(dictionary.contains(currWord))
                    System.out.println(currWord);
            }
        }
    }
    public static void main(String[] args)
    {
        board = createBoard();
        ArrayList<String> validWords = RandomWordGame.solver(board);
        for(String word : validWords)
            System.out.println(word);
    }
}

最佳答案

此代码有些有趣的地方。首先,您总是从求解器方法返回一个空的ArrayList,但这并不是杀死您的原因,因为您正在打印findWords中的每个结果。

问题是findWords方法只是从拼图的左上方连续添加字母。

//i=0 and j=0 means it will always start at the top left tile
for(i=0; i>=0 && i<board.length; i++)
{
    for(j=0; j>=0; j++)
    {
        //currWord is never reset, so it just keeps getting longer
        currWord += board[i][j];
        if(currWord.length()>5)
            return;
        if(dictionary.contains(currWord))
            System.out.println(currWord);
    }
}


现在,您只会找到以所选图块开头的单词,其余字母的选择顺序与从左上角开始添加到拼图的顺序相同。

我建议您花些时间在铅笔和纸上,并深入了解二维数组索引与其在网格中的位置之间的关系。

10-06 06:08