我在尝试使某个 for 循环继续完成 1D Queens 问题时遇到了麻烦。
首先,我对所有内容都使用了 goto 语句。现在我试图通过使用函数来摆脱 goto 语句。我最终会摆脱所有这些,但我首先关注的是 NR(新行)和回溯,因为它们是用来互相调用的。
我遇到问题的 for 循环是检查一个位置是否对皇后安全的循环。我在评论中指出了未完成的 for 循环。
//forward declarations
int backtrack (int board[], int& c_position);
//NR: q[c]++;
//if (q[c]==8) goto backtrack;
void NR (int board[], int& c_position) //new row
{
board[c_position]++;
if (board[c_position]==8) {backtrack(board, c_position);}
}
int backtrack (int board[], int& c_position) // backtrack
{
c_position--;
if (c_position==-1) {system("PAUSE"); exit(1);}
NR(board, c_position);
}
int main ()
{
int q[8] = {0}; //1D array, the board, all set to 0;
int c=0;
int count=0;
NC: c++; //new column
if (c==8) goto print;
q[c]=-1;
NR(q, c);
//test to see if position is safe
for (int i=0; i<c; i++) //this is the for loop I am having trouble with
{
if ( (q[i]==q[c]) || ((c-i)==abs(q[c]-q[i])) ) { NR(q, c); }
}
goto NC;
print: //printing the 1D board gives us a single line, where each number represents a row where a queen is
count++;
cout << count << endl;
for(int j = 0; j <= 7; j++)
{
cout << q[j] << " ";
}
cout << endl;
backtrack(q, c);
system("PAUSE"); return 0;
}