八皇后问题

来源:互联网 发布:vb中index 编辑:程序博客网 时间:2024/05/29 09:05
#include<iostream>
#include<math.h>
using namespace std;
int a[8], flag = 1, c= 1;
void search(int row);
int complies(int row, int cot);
void output();
int main(void)
{
 search(0);
 system("pause");
 return 0;
}
void search(int row)
{
 if (row == 8)
 {
  cout << "No" << ' '<<c << ':' << endl;
  output();
  c++;
 }
 else
 {
  for (int cot = 0; cot < 8; cot++)
  {
   if (complies(row, cot) == 1)
   {
    a[row] = cot;
    search(row + 1);
   }
  }
 }
}
int complies(int row, int cot)
{
 flag = 1;
 for (int i = 0; i < row; i++)
 {
  if (a[i] == cot || abs(row - i) == abs(a[i] - cot))
   flag = 0;
 }
 return flag;
}
void output()
{
 for (int i = 0; i < 8; i++)
 {
  for (int j = 0; j < 8; j++)
  {
   if (j == a[i]) cout << 'A';
   else cout << '.';
  }
  cout << endl;
  
 }
}
原创粉丝点击