作業是完成8皇后2維陣列程序與回溯。我做了這個程序是否正確?
#include <iostream>
using namespace std;
int main() {
int b[8][8] = { 0 };
int r, c, i;
int count = 1;
b[0][0] = 1;
c = 0;
nextColumn:
c++;
if (c == 8)
goto print;
r =- 1;
nextRow:
r++;
if (r == 8)
goto back;
for (i = 0; i < c; i++) {
if (b[r][i] == 1)
goto nextRow;
}
for (i = 0; (r - i) >= 0 && (c - i) >= 0; i++) {
if (b[r - i][c - i] == 1)
goto nextRow;
}
for (i = 0; (r + i) < 8 && (c - i) >= 0; i++) {
if (b[r + i][c - i] == 1)
goto nextRow;
}
b[r][c] = 1;
goto nextColumn;
c--;
if (c == -1)
return 0;
r = 0;
while (b[r][c] != 1)
r++;
b[r][c] = 0;
goto nextRow;
cout << endl;
cout << "Result No." << count << endl;
cout << endl;
for (r = 0; r < 8; r++){
for (int c = 0; c < 8; c++){
cout << b [r][c];
}
cout << endl;
}
count++;
goto back;
}
那麼,「它產生正確的解決方案」和「使用回溯」? (我猜測代碼中有些東西是「錯誤的」。) – 2011-07-14 03:40:13
* gasp *,看看所有那些goto的馬! – greatwolf