8 Queens Chess Problem
阿新 • • 發佈:2019-02-15
題目:八皇后模型,輸出包含了某一點的所有皇后
注意:格式上,不同輸入之間空兩行。數字的最後沒有空格,所以把空格寫在前面。還有最後一行輸出後,後面沒有空行了
#include <cstdio> #include <string.h> #include <cstdlib> #include <cmath> #include <ctgmath> #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int xunhuan; cin>> xunhuan; while(xunhuan--){ int x,y; cin >> x >> y; int t = 1; int a[8] = {0}; int b[15] = {0}; int c[15] = {0}; int j = 0,i=0; int temp = 0; int count = 1; vector<int> m; vector<int>::iterator it; vector<int> sum; cout<<"SOLN COLUMN"<<endl; cout<<" # 1 2 3 4 5 6 7 8"<<endl<<endl; while(1){ for(i = 0; i <= 7; i ++){ for(j = 0; j <= 7; j ++){ if((a[j]==0) && (b[i+j]==0) && (c[i-j+7]==0) ){//這一點可以有皇后 m.push_back(j); a[j]=1; b[i+j]=1; c[i-j+7]=1; break; } } //如果走完了還沒有位置 if(j == 8){ Next_One: while(1){ if(i >= 0){ i--; temp = m[i]; //刪除原來皇后的記錄 a[temp]=0; b[i+temp]=0; c[i-temp+7]=0; m.pop_back(); for(j = temp +1; j <= 7; j ++){ if((a[j]==0) && (b[i+j]==0) && (c[i-j+7]==0) ){//這一點可以有皇后 m.push_back(j); a[j]=1; b[i+j]=1; c[i-j+7]=1; break; } } if(j != 8) break; } } } } //判斷 if(m[y-1] == x-1){ printf("%2d",count++); cout<<" "; for(it = m.begin();it != m.end();it++){ cout << " " << (*it)+1; //空格在之前出現 } cout<<endl; } t++; if(t==93) break; goto Next_One; } // goto Next_One; if(xunhuan)cout<<endl; //先判斷是不是最後一行了,否則不輸出回車 } return 0; }