2013-02-19 63 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的)循環嘗試增加它。

無論如何,這就是我更仔細看的。