I am currently writing a game that finds an inputted word in matrix in snaky-ways. Here is a brief explanation for the game.
User will first asked to enter a filename that contains lines to create a matrix. After the creation, user will asked to input a word to be searched in that matrix. The search is only towards south, east and southeast. If it founds the word, displays the coordinates and show some message. An example matrix is below:
m e r e t z
e x i t a v
p p w a b i
y u u b l l
a l l l a l
z k v e l o
I have managed to search words like “exit” in this matrix but my problem is words like “mere” or “table”. In my algorithm, I can only search for words that doesn’t have the same letter in two directions. I couldn’t find a proper way to do it.
Here is the search part of my code.
bool Search(tmatrix<char>& m, tmatrix<int>& c, const string& w, int i, int j, int index) // m is the matrix to search in // w is the word // i and j are coordinates of matrix {
if(m[i][j] == w[index])
{
c[index][0] = i; // c matrix is to keep coordinates of words
c[index][1] = j;
if(index != w.length()-1)
{
if((i < m.numrows()-1) && (m[i+1][j] == w[index+1]))
return Search(m, c, w, i+1, j, index+1);
else if((j < m.numcols()-1) && (i < m.numrows()-1) && (m[i+1][j+1] == w[index+1]))
return Search(m, c, w, i+1, j+1, index+1);
else if((j < m.numcols()-1) && (m[i][j+1] == w[index+1]))
return Search(m, c, w, i, j+1, index+1);
else
return false;
}
else
return true;
}
return false;
}
int main()
{
bool IsFound = false; //to check whether the word is found or not in the matrix
tmatrix<int> coord(word.length(), 2); //another matrix to keep coordinates of found word's coordinates.
//it works with the index of words and the row index of matrix.
for(int i = 0; i < m.numrows(); i++)
{
for(int j = 0; j < m.numcols(); j++)
{
int index = 0; //another variable to keep index number
IsFound = Search(m, coord, word, i, j, index); //searches matrix for word and if found, makes IsFound's return value true
if(IsFound)
{
cout << "The word "<< word << " is found!\n";
cout << "Indices in which this word is found in the matrix are:\n";
for(; index < word.length(); index++)
{
cout << word[index] << ":\t" << coord[index][0] << "," << coord[index][1] << endl;
}
break; //whenever it finds a match in matrix, it finishes search in loops
}
}
if(IsFound)
break;
}
}
It only goes to the direction that firstly appears on the if statement list. Changing else ifs to if didn’t work for me.
Changing the function into this solved all my problems. Thanks for your comment, they inspired me.