我的目标是从5x5矩阵中找到长度为2到5个字母的所有单词。我的搜索方法有效,但它不适用于字典中的每个单词。
搜索方法:
public static void Search(char board[][])
{
int X = board.length;
int Y = board[0].length;
//Mark all characters as not visited
boolean visited[][] = new boolean[X][Y];
//Initialize current string
String str = "";
//Consider every character and look for all words
//starting with this character
for(int i=0;i<X;i++)
{
for(int j=0;j<Y;j++)
{
System.out.println("Starting at: "+i+" "+j);
WordsFound(board, visited, i, j, str);
}
}
}
WordsFound方法:
public static void WordsFound(char board[][], boolean visited[][], int i, int j, String str)
{
visited[i][j] = true;
if(str.length() == 5)
return;
str = str + board[i][j];
//If the word is present in dictionary, then print it
if(isWord(str))
System.out.println("Found Word: "+str);
int X = board.length;
int Y = board[0].length;
//Search the word in the 5 by 5 matrix.
for(int row=i-1;row<=i+1 && row<X;row++)
{
for(int col=j-1;col<=j+1 && col<Y;col++)
{
if(row>=0 && col>=0 && !visited[row][col])
//Call the method WordsFound.
WordsFound(board,visited, row, col, str);
}
}
if(str != null && str.length() > 0 )
{
str = str.substring(0, str.length()-1);
}
visited[i][j] = false;
}
主要课程:
public static void main(String[] args) throws FileNotFoundException
{
readFile("dictionary.txt");
char board[][] = {
{'R','A','H','J','M'},
{'Y','U','W','W','K'},
{'R','X','N','F','M'},
{'Q','G','E','E','B'},
{'E','O','A','P','E'}};
System.out.println("R A H J M\nY U W W K\nR X N F M\nQ G E E B\nE O A P E");
System.out.println("");
Search(board);
}
我的程序确实找到了&#34; RAW&#34;但为什么它没有找到&#34; RUN&#34;?
这个词运行程序只显示索引0 0:
R A H J M
Y U W W K
R X N F M
Q G E E B
E O A P E
Starting at: 0 0
Found Word: RAY
Found Word: RAW
答案 0 :(得分:0)
要查找“RUN”,您需要确保当您处于“U”状态时,尚未访问“N”,否则您将无法访问该单元格。
但是由于你正在运行dfs,“N”单元格可能已经从它周围的单元格访问而不是“U”,这将设置visited
为“N”为真,并从“U”搜索会失败。
要解决此问题,您需要拥有3D visited
,除了索引之外,您还需要存储到目前为止遍历的路径。 (即到目前为止的字符串)
int
和string
的复杂性正如我为visited
变量所建议的那样。只需使用字符串的散列而不是直接字符串,它也将节省大量空间。