剑指offer系列源码-八皇后问题 C语言

来源:互联网 发布:linux系统内核裁剪 编辑:程序博客网 时间:2024/04/28 23:11

 题目:在8×8的国际象棋上摆放八个皇后,使其不能相互攻击,即任意两个皇后不得处在同一行、同一列或者同一对角斜线上。下图中的每个黑色格子表示一个皇后,这就是一种符合条件的摆放方法。请求出总共有多少种摆法。


    这就是有名的八皇后问题。解决这个问题通常需要用递归,而递归对编程能力的要求比较高。因此有不少面试官青睐这个题目,用来考察应聘者的分析复杂问题的能力以及编程的能力。

由于八个皇后的任意两个不能处在同一行,那么这肯定是每一个皇后占据一行。于是我们可以定义一个数组ColumnIndex[8],数组中第i个数字表示位于第i行的皇后的列号。先把ColumnIndex的八个数字分别用0-7初始化,接下来我们要做的事情就是对数组ColumnIndex做全排列。由于我们是用不同的数字初始化数组中的数字,因此任意两个皇后肯定不同列。我们只需要判断得到的每一个排列对应的八个皇后是不是在同一对角斜线上,也就是数组的两个下标i和j,是不是i-j==ColumnIndex[i]-Column[j]或者j-i==ColumnIndex[i]-ColumnIndex[j]。

思路想清楚之后,编码并不是很难的事情。下面是一段参考代码:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include<stdio.h>  
  3. using namespace std;  
  4. int total = 0;  
  5. bool check(int columnIndex[],int length){  
  6.     for(int i=0;i<length;i++){  
  7.         for(int j=i+1;j<length;j++){  
  8.             //是否在对角线上  
  9.             if(i-j==columnIndex[i]-columnIndex[j]||j-i==columnIndex[i]-columnIndex[j]){  
  10.                 return false;  
  11.             }  
  12.         }  
  13.     }  
  14.     return true;  
  15. }  
  16. //全排列  
  17. void Permutation(int columnIndex[],int length,int index){  
  18.     if(length==index){  
  19.         if(check(columnIndex,length)){  
  20.             total++;  
  21.             //打印  
  22.             for(int i=0;i<length;i++){  
  23.                 printf("%d ",columnIndex[i]);  
  24.             }  
  25.             printf("\n---------------------------\n");  
  26.         }  
  27.     }else{  
  28.         for(int i= index ;i<length;i++){  
  29.             swap(columnIndex[index],columnIndex[i]);  
  30.             Permutation(columnIndex,length,index+1);  
  31.             swap(columnIndex[index],columnIndex[i]);  
  32.         }  
  33.     }  
  34. }  
  35. void eightQueen(){  
  36.     int queens =8;  
  37.     int* columnIndex = new int[queens];  
  38.     for(int i=0;i<queens;i++){  
  39.         columnIndex[i] = i;  
  40.     }  
  41.     Permutation(columnIndex,queens,0);  
  42. }  
  43. int main()  
  44. {  
  45.     eightQueen();  
  46.     printf("共有%d种",total);  
  47.     return 0;  
  48. }  
0 0
原创粉丝点击