- /*
- 需要注意,判断x,y位置是否有棋子时,x>y 与x<y时情况不一样,需要及时跳出循环。
- */
- #include<iostream>
- #include<cstring>
- using namespace std;
- int n;
- int chess[14][14];
- int num=0;
- bool ifco(int x,int y){
- for(int i=0;i<x;i++){
- if(chess[i][y]==1){
- return false;
- }
- }
- if(x>=y){
- for(int j=0;j<y;j++){
- if(chess[x-y+j][j]==1){
- return false;
- }
- }
- for(int j=y+1;j<n;j++){
- if(x+y-j<0)break;
- if(chess[x+y-j][j]==1){
- return false;
- }
- }
- }else{
- for(int i=0;i<x;i++){
- if(chess[i][y-x+i]==1){
- return false;
- }
- }
- for(int j=y+1;j<n;j++){
- if(x+y-j<0)break;
- if(chess[x+y-j][j]==1){
- return false;
- }
- }
- }
- return true;
- }
- bool ifcould(int x,int y){
- int flag=true;
- int ic=false;
- for(int i=0;i<n;i++){
- for(int j=0;j<n;j++){
- if(i>=x){
- ic=true;
- break;
- }
- if(j==y&&chess[i][j]==1){
- ic=true;
- flag=false;
- break;
- }
- if(x+y==i+j&&chess[i][j]==1){
- ic=true;
- flag=false;
- break;
- }
- if(x-y==i-j&&chess[i][j]==1){
- ic=true;
- flag=false;
- break;
- }
- }
- if(ic)break;
- }
- return flag;
- }
- void put(int x){
- if(x>=n){
- num++;
- return ;
- }
- for(int i=0;i<n;i++){
- if(ifco(x,i)){
- chess[x][i]=1;
- put(x+1);
- chess[x][i]=0;
- }
- }
- }
- int main(){
- cin>>n;
- //n=8;
- memset(chess,0,sizeof(chess));
- put(0);
- cout<<num<<endl;
- return 0;
- }
n皇后
最新推荐文章于 2023-12-06 19:41:23 发布