My objective is to find all words 2 to 5 letters in length from a 5x5 matrix. my search method works but it does not work for every word in the dictionary.
Search method:
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 method:
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;
}
main class:
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);
}
My program does find the word "RAW" but why doesn't it find the word "RUN"?
Running the program just showing the index 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