2013-02-19 64 views
-2

我在尝试使一个for循环在1D Queens问题中继续完成时遇到问题。如何完成这个调用函数的for循环

首先,我使用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; 

} 
+0

我的建议:不要以'goto's开头。 – 2013-02-19 14:47:04

回答

1

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

这似乎阻止你(基于外部goto的)循环尝试增加它。

无论如何,这就是我更仔细看的。