【发布时间】:2012-03-05 00:28:28
【问题描述】:
我目前正在编写一个游戏,它以蛇形方式在矩阵中查找输入的单词。以下是游戏的简要说明。
用户将首先要求输入包含行的文件名以创建矩阵。创建后,用户将要求输入要在该矩阵中搜索的单词。搜索只针对南、东和东南。如果它找到了单词,则显示坐标并显示一些消息。下面是一个示例矩阵:
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
我已经设法在这个矩阵中搜索“exit”之类的词,但我的问题是“mere”或“table”之类的词。在我的算法中,我只能在两个方向上搜索没有相同字母的单词。我找不到合适的方法来做到这一点。
这是我的代码的搜索部分。
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;
}
}
它只指向首先出现在 if 语句列表中的方向。将else ifs 更改为if 对我不起作用。
【问题讨论】: