八皇后问题—递归求解

 

 

 

  1 //八皇后:递归
  2 #include <stdio.h>
  3 
  4 int count=0;
  5 //判断第row行第column列有没有危险:可以存放Queen?
  6 //int (*chess)[8]:指向某一行的指针,8表示列数
  7 int notDanger(int row,int column,int (*chess)[8])
  8 {
  9     int i, j;
 10     //判断列
 11     for (i = 0; i < 8;i++)
 12     {
 13         if(*(*(chess+i)+column)!=0)
 14             return 0;
 15     }
 16     //判断行
 17     for (i = 0; i < 8;i++)
 18     {
 19         if(*(*(chess+row)+i)!=0)
 20             return 0;
 21     }
 22     //判断左上方
 23     for (i = row, j = column; i >= 0 && j >= 0;i--,j--)
 24     {
 25         if(*(*(chess+i)+j)!=0)
 26             return 0;
 27     }
 28     //判断右下方
 29     for (i = row, j = column; i <8 && j < 8;i++,j++)
 30     {
 31         if(*(*(chess+i)+j)!=0)
 32             return 0;
 33     }
 34     //判断右上方
 35     for (i = row, j = column; i >= 0 && j < 8;i--,j++)
 36     {
 37         if(*(*(chess+i)+j)!=0)
 38             return 0;
 39     }
 40     //判断左下方
 41     for (i = row, j = column; i < 8 && j >= 0;i++,j--)
 42     {
 43         if(*(*(chess+i)+j)!=0)
 44             return 0;
 45     }
 46     return 1;
 47 }
 48 //参数row:表示起始行
 49 //参数column:表示列
 50 //参数int (*chess)[8]:指向每一行的指针,8表示列数
 51 //安排第row行存放Queen:一行一行往下安排,直到第8行安排完毕
 52 void EightQueen(int row,int column,int (*chess)[8])
 53 {
 54     //临时数组
 55     int chess2[8][8];
 56     int i, j;
 57     for (i = 0; i < 8; i++)
 58     {
 59         for (j = 0; j < 8;j++)
 60             chess2[i][j] = chess[i][j];
 61     }
 62     if(row==8)
 63     {
 64         printf("第%d种\n", count + 1);
 65         for (i = 0; i < 8; i++)
 66         {
 67             for (j = 0; j < 8;j++)
 68             {
 69                 printf("%d ", *(*(chess2 + i) + j)); 
 70             }
 71             printf("\n");
 72         }
 73         printf("\n");
 74         count++;
 75     }
 76     else
 77     {
 78         for (i = 0; i < column;i++)
 79         {
 80             if(notDanger(row,i,chess))
 81             {
 82                 for (j = 0; j < 8;j++)
 83                 {
 84                     *(*(chess2 + row) + j) = 0;
 85                 }
 86                 *(*(chess2 + row) + i) = 1;
 87                 EightQueen(row + 1, column, chess2);
 88             }
 89         }
 90     }
 91 }
 92 
 93 int main()
 94 {
 95     int chess[8][8];
 96     int i, j;
 97     //二维数组初始化为0
 98     for (i = 0; i < 8; i++)
 99     {
100         for (j = 0; j < 8;j++)
101             chess[i][j] = 0;
102     }
103 
104     EightQueen(0,8,chess);
105     return 0;
106 }
View Code

 

posted @ 2020-08-30 12:54  wind_y  阅读(116)  评论(0编辑  收藏  举报