写了一个八皇后问题的代码

经典的问题,不过以前没有做过,今天动手写了一个,效率不是很高,但思想是有一点的,最主要是判断斜线的方法,用x+y和x-y来判断。

   1: #include <iostream>
   2:  
   3: using namespace std;
   4: #define N 8
   5:  
   6: void show(int A[N][N])
   7: {
   8:     static int count = 0;
   9:     cout << ++count << endl;
  10:     for (int i = 0; i < N; i++)
  11:     {
  12:         for (int j = 0; j < N; j++)
  13:         {
  14:             if (A[i][j] == 1)
  15:             {
  16:                 cout << "W ";
  17:             }
  18:             else
  19:             {
  20:                 cout << "- ";
  21:             }
  22:         }
  23:         cout << endl;
  24:     }
  25:     cout << endl;
  26: }
  27:  
  28: bool check(int A[N][N], int x, int y)
  29: {
  30:     int sum = x + y;
  31:     int sub = x - y;
  32:     for (int i = 0; i < N; i++)
  33:     {
  34:         if (x != i && A[i][y] == 1)
  35:         {
  36:             return false;
  37:         }
  38:         for (int j = 0; j < N; j++)
  39:         {
  40:             if (j == y)
  41:             {
  42:                 continue;
  43:             }
  44:             if (A[x][j] == 1)
  45:             {
  46:                 return false;
  47:             }
  48:             if (i + j == sum && A[i][j] == 1)
  49:             {
  50:                 return false;
  51:             }
  52:             if (i - j == sub && A[i][j] == 1)
  53:             {
  54:                 return false;
  55:             }
  56:         }
  57:     }
  58:  
  59:     return true;
  60: }
  61:  
  62: void putQueen(int A[N][N], int row)
  63: {
  64:     if (row >= N)
  65:     {
  66:         show(A);
  67:         return;
  68:     }
  69:  
  70:     for (int i = 0; i < N; i++)
  71:     {
  72:         A[row][i] = 1;
  73:  
  74:         if (check(A, row, i) != false)
  75:         {
  76:             putQueen(A, row + 1);
  77:         }
  78:  
  79:         A[row][i] = 0;
  80:     }
  81:  
  82:     return;
  83: }
  84:  
  85: void run(int x[N][N])
  86: {
  87:      putQueen(x, 0);
  88: }
  89:  
  90: int main()
  91: {
  92:     int X[N][N] = {0};
  93:     run(X);
  94:     system("pause");
  95:     return 0;
  96: }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值