是一个以国际象棋为背景的问题:如何能够在 8×8 的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后?为了达到此目的,任两个皇后都不能处于同一条横行、纵行或斜线上。八皇后问题可以推广为更一般的n皇后摆放问题:这时棋盘的大小变为n×n,而皇后个数也变成n。当且仅当 n = 1 或 n ≥ 4 时问题有解。
- /*
- * Copyright (c) leo
- * All rights reserved.
- * filename: nQueens
- * summary :
- * version : 1.0
- * author : leo
- * date : 8.12.2011
- *问题:
- * 在n*n (n=1 or n>=4 )的棋盘上放置n个皇后,如果在同一行,同一列,同一对角线上都不存在两个皇后,
- * 那么这个棋盘格局就是n皇后的一个解。
- *要求:
- * 找出n皇后的一组解即可,打印出放置满足n皇后条件的棋子位置
- */
- #include<stdio.h>
- #include<math.h>
- #include<stdlib.h>
- #include<conio.h>
- #define N 8 //皇后数=棋盘行列数
- int a[N]; //a[i]为第i行皇后所在列
- void show() //图形化输出
- {
- int i;
- int p,q ;
- int b[N][N]={0};
- static t=1;
- printf("第%d个解为: ",t++);
- for(i=0;i<N;i++)
- {
- b[i][a[i]]=1;
- printf("(%d,%d) ",i,a[i]);
- }
- printf("\n");
- for(p=0;p<N;p++)
- {
- for(q=0;q<N;q++)
- {
- if(b[p][q]==1)
- printf("●");
- else
- printf("○");
- }
- printf("\n");
- }
- }
- int check(int n) //满足条件返回1,否则返回0
- {
- int i;
- for(i=0;i<n;i++)
- {
- if(a[i]==a[n]||fabs(n-i)==fabs(a[i]-a[n])) //at the same column or diagonal (对角线)
- return 0;
- }
- return 1;
- }
- void put(int n) //在第n行放置第n个皇后
- {
- int i;
- if(n==N)
- return ;
- for(i=0;i<N;i++)
- {//此处循环一直到N,循环,嵌套
- a[n]=i;
- if(check(n)) //位置合法
- {
- if(n==N-1) //皇后全部放置完毕
- show();
- else
- put(n+1);
- }
- }
- }
- int main ()
- {
- put(0);
- return 0;
- }