• 25.八皇后问题


    思路:按行扫描,一维数组下标代表行,所表示的值代表所在的列,依次递归进行判断

    代码:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <math.h>
     4 
     5 #define N 8
     6 int a[N];//a[i]第i行的皇后所在的列
     7 
     8 void show()
     9 {
    10     int data[N][N] = { 0 };
    11     //标识第几次解
    12     static int t = 1;
    13     printf("第%d个解法
    ", t);
    14     for (int i = 0; i < N; i++)
    15     {
    16         //皇后的位置设置为1
    17         data[i][a[i]] = 1;
    18     }
    19     //显示
    20     for (int i = 0; i < N; i++)
    21     {
    22         for (int j = 0; j < N; j++)
    23         {
    24             if (data[i][j] == 1)
    25             {
    26                 printf("");
    27             }
    28             else
    29             {
    30                 printf("");
    31             }
    32         }
    33         printf("
    ");
    34     }
    35     t++;
    36 }
    37 
    38 int check(int n)
    39 {
    40     for (int i = 0; i < n; i++)
    41     {
    42         //判断之前行数所在的列是否和当前行数的列冲突
    43         //如果某两行的距离与某两列的差距一样,则说明在对角线了
    44         if (a[i] == a[n] || fabs(n-i) == fabs(a[n]-a[i]))
    45         {
    46             return 0;
    47         }
    48     }
    49     return 1;
    50 }
    51 
    52 //求解
    53 void getqueen(int n)
    54 {
    55     if (n == N)
    56     {
    57         return;
    58     }
    59     //每一行的皇后所在的列从0到N-1依次赋值,再进行合法性判断
    60     for (int i = 0; i < N; i++)
    61     {
    62         a[n] = i;
    63         //合法
    64         if (check(n))
    65         {
    66             //如果所有行数都遍历完
    67             if (n == N - 1)
    68             {
    69                 //显示
    70                 show();
    71                 system("pause");
    72             }
    73             else
    74             {
    75                 //遍历下一行
    76                 getqueen(n + 1);
    77             }
    78         }
    79     }
    80 }
    81 
    82 void main()
    83 {
    84     //求解
    85     getqueen(0);
    86     system("pause");
    87 }
  • 相关阅读:
    Markdown基本语法
    面向对象
    LeetCode739 每日温度
    LeetCode155 最小栈
    LeetCode279 完全平方数
    LeetCode752 打开转盘锁
    LeetCode622 设计循环队列
    LeetCode200 岛屿的个数
    LeetCode61 旋转链表
    LeetCode138 复制带随机指针的链表
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8519426.html
Copyright © 2020-2023  润新知