我深知,這代碼是沒有效率的......我是新的C++,這是我在解決方案的第一槍對角線測試...8個皇后
的問題是,當我運行該程序將返回無結果。我試過調試,似乎我的問題是在對角線測試...
我意識到當我設置slope == 1或slope == - 1時,它會給出480個結果,但是當我設置slope == 1 || slope == - 1它沒有結果。我覺得我在邏輯上錯過了一些東西。所以我認爲問題出現在我的功能衝突的最後部分。
#include <iostream>
#include <cmath>
using namespace std;
void print (bool a[8][8]){
for (int r=0; r<8; r++){
for (int c=0; c<8; c++){
if (a[r][c]==true) cout<<"X";
else cout<<"E";
}
cout<<endl;
}
}
void XYdivide (bool a[][8], int xplace[], int yplace[]){
int uptonumber=0;
for (int r=0; r<8; r++){
for (int c=0; c<8; c++){
if (a[c][r]) { yplace[uptonumber]=c; xplace[uptonumber]=r; uptonumber++;}
}
}
}
bool clash (bool a[8][8]){
static int total=1;
int Columncounter;
for (int r=0; r<8; r++){ //tests columns
Columncounter=0;
for (int c=0; c<8; c++){
if (a[r][c]) Columncounter++;
if (Columncounter>1) return false;
}
}
int Rowcounter;
for (int c=0; c<8; c++){ //tests rows
Rowcounter=0;
for (int r=0; r<8; r++){
if (a[r][c]) Rowcounter++;
if (Rowcounter>1) return false;
}
}
int xvalues [8]; int yvalues[8];
XYdivide(a , xvalues, yvalues);
for (int i=0; i<8; i++){ //test diagonals
for (int j=0; j<8; j++){
int slope=(yvalues[i]-yvalues[j])/(0.0+xvalues[i]-xvalues[j]);
if (slope==-1 || slope==1) return false;
}
}
print (a); cout<<endl<<total++<< endl; return true;
}
int main(){
bool a[8][8]={false};
cout<<"starting"<<endl;
for (int r0=0; r0<8; r0++){
a[0][r0]=true;
if (r0>0) a[0][r0-1]=false;
for (int r1=0; r1<8; r1++){
a[1][r1]=true;
if (r1>0) a[1][r1-1]=false;
if (r1==0) a[1][7]=false;
for (int r2=0; r2<8; r2++){
a[2][r2]=true;
if (r2>0) a[2][r2-1]=false;
if (r2==0) a[2][7]=false;
for (int r3=0; r3<8; r3++){
a[3][r3]=true;
if (r3>0) a[3][r3-1]=false;
if (r3==0) a[3][7]=false;
for (int r4=0; r4<8; r4++){
if (r4>0) a[4][r4-1]=false;
if (r4==0) a[4][7]=false;
a[4][r4]=true;
for (int r5=0; r5<8; r5++){
a[5][r5]=true;
if (r5>0) a[5][r5-1]=false;
if (r5==0) a[5][7]=false;
for (int r6=0; r6<8; r6++){
a[6][r6]=true;
if (r6>0) a[6][r6-1]=false;
if (r6==0) a[6][7]=false;
for (int r7=0; r7<8; r7++){
a[7][r7]=true;
if (r7>0) a[7][r7-1]=false;
if (r7==0) a[7][7]=false;
clash(a);
}
}
}
}
}
}
}
}
return 0;
}
我真的不認爲你想要的8級循環。 :s – 2015-02-06 15:59:13
它似乎很好地工作。是的,因爲我寫道:這是我的第一次嘗試,效率很低! – 2015-02-06 16:03:55
更有效率的方法是在每次添加另一塊棋子時檢查衝突,假設之前沒有衝突。在這種情況下,您只需檢查新件上相交的線,而不是檢查整個板。 – Dialecticus 2015-02-06 16:07:24