#include<iostream> #include<math.h> using namespace std; using std::cout; const int size=8; int abs(int x) { return (x>0?x:-x); } bool isValid(int *data,int row,int col) { for(int i=0;i!=row;i++) { if(data[i]==col||(abs(row-i)==abs(col-data[i]))) { return false; } } return true; } void placeQueen(int row,int *data) { if(row==size) { cout<<"solution:"; for(int i=0;i!=size;i++) { cout<<" "<<i<<" "<<data[i]<<" "; } cout<<endl; } else { for(int col=0;col!=size;col++) { if(isValid(data,row,col))//0~(row-1)的皇后已经放好了 { data[row]=col; placeQueen(row+1,data); } } } } int main() { int data[8]={0}; placeQueen(0,data); }
原文地址:http://blog.csdn.net/hero_zouzongling/article/details/45890299