• N皇后问题


    N皇后问题是一个经典的问题,在一个N*N的棋盘上放置N个皇后,每行一个并使其不能互相攻击(同一行、同一列、同一斜线上的皇后都会自动攻击)

     1 #include <iostream> 
     2 #include <cmath>
     3 using namespace std; 
     4  
     5 #define N 4
     6  
     7 bool matrix[N + 1][N + 1] = {0}; 
     8  
     9 bool IsLegal(bool matrix[N + 1][N + 1], const int &i, const int &j) 
    10 { 
    11     //  判断前面的i-1个棋子与matrix[i][j]是否冲突,i为1时合法 
    12  
    13     for (int m = 1; m <= i - 1; ++m) { 
    14         for (int n = 1; n <= N; ++n) {   //  实际每一行只有一个棋子 
    15             if (matrix[m][n] == 1) { 
    16                 if ( n == j || abs(i - m) == abs(j - n) )   //  key, not bad 
    17                     return false; 
    18             } 
    19         } 
    20     } 
    21     return true; 
    22 } 
    23  
    24 void Print(bool matrix[N + 1][N + 1]) 
    25 { 
    26     static int count = 1; 
    27     printf("Case %d:
    ", count++); 
    28     for (int i = 1; i <= N; i++) { 
    29         for (int j = 1; j <= N; j++) { 
    30             matrix[i][j] == 1 ? printf("%c ", 2) : printf(". "); 
    31         } 
    32         cout << endl; 
    33     } 
    34     cout << endl; 
    35 } 
    36  
    37 void Trial(const int i) 
    38 { 
    39     //  进入本函数时,在N*N的棋盘前i-1行已放置了互不攻击的i-1个棋子 
    40     //  现从第i行起继续为后续棋子选择合适位置 
    41  
    42     if (i > N)   //  输出当前的合法布局 
    43         Print(matrix); 
    44     else 
    45         for (int j = 1; j <= N; ++j) { 
    46             matrix[i][j] = 1; 
    47             if ( IsLegal(matrix, i, j) ) 
    48                 Trial(i + 1); 
    49             matrix[i][j] = 0; 
    50         } 
    51 } 
    52  
    53 int main(void) 
    54 { 
    55     Trial(1); 
    56  
    57     return 0; 
    58 }

    打印结果:

  • 相关阅读:
    javascript 创建字典
    IE显示PNG
    透明PNG背景图片 For IE 6.0 Firefox Opera
    IE FireFox对CSS的不同解释收集
    javascript中replace()
    netstat 指令返回结果中state含义
    FIREFOX层的自适应高度
    select options的操作
    事件冒泡
    C++第三讲笔记
  • 原文地址:https://www.cnblogs.com/wxdjss/p/5448802.html
Copyright © 2020-2023  润新知