如何完成这个调用函数的 for 循环

How to complete this for-loop that calls a function

本文关键字:for 循环 函数 调用 何完成      更新时间:2023-10-16

我在尝试使某个 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;
}

您通过引用传递c的函数,该函数将其传递给另一个递减它的函数。

这似乎挫败了(基于外部goto(循环增加它的尝试。

无论如何,这就是我要更仔细地研究的内容。