我目前正在尝试使用回溯来生成单词在 2D 向量中可能具有的所有不同位置。
假设我有一个包含单词“Hello”的向量(出于记忆原因,我更喜欢使用它,因为我将处理很多单词)。
我生成一个 '.' 的二维向量。字符 5x5 宽(所以它可以适合这个词)。
然后使用回溯算法,我想生成这个单词可以占据的所有位置,而字母仍然相互链接。
例如 :
. . . . . . . . . . . . . . .
H e . . . or . . . H . or even . . . . .
. l . . . . . o e . . . . . .
. l o . . . . l l . . . . . .
. . . . . . . . . . o l l e H
我对一维感兴趣的算法是(伪代码):
function solve(word vector, size of vector)
if end of word vector
Print vector obtained
else for choice possible do
if Choice is admissible then
Build partial Candidate according to Choice
Test(i + 1)
Undo Choice
这个伪代码可以给出一个单词中不同的字母组合。我正在尝试对其进行调整以使其执行之前解释的操作。
可悲的是,我执行错误,因为我根本没有获得预期的结果:没有打印。我很乐意阅读您对此的评论和意见。
这是我到目前为止所做的:
回溯功能:
// All the arguments of the function are correctly defined in the main, with i, j, k set to zero.
bool backtracking(vector<vector<char> > vect , vector <char> word,int n, int i, int j, int k) {
if(k==n) // If the end of the word is reached
{
print_grid(vect); //Prints the 2D vector with the word included
return true;
}
else
{
if(admissible_choice(vect, n, i, j) == true) // If choice is admissible
{
vect[i][j] = word[k]; // Builds partial candidate
if (backtracking(vect,word,n,i+1,j,k)==true) // Moves in the i-direction
{ k++; // If true, goes to the next element of the chain
return true; }
if (backtracking(vect,word,n,i,j+1,k)==true) // Moves in the j direction
{ k++;
return true; }
else
{ vect[i][j] = '.'; // Backtrack, if no condition verified then fills the 2D vector with points
return false; }
}
return false;
}
}
打印功能
void print_grid(vector<vector<char> > vect) {
for (int i = 0; i < vect.size(); i++) {
for (int j = 0; j < vect[i].size(); j++) {
cout << vect[i][j];
}
cout<<""<<endl;
}
cout<<"\n"<<endl;
}
确定可接受选择的功能
bool admissible_choice(vector<vector<char> > vect, int n, int i, int j)
{
if(i >= 0 && i < n && j >= 0 && j < n && vect[i][j] == '.')
{ return true;}
else
{ return false;}
}
提前感谢您提供的所有帮助!