#include <iostream>
#include <math.h>
using namespace std;
#define N 8
bool workPosition(int pos[N], int currentRow, int currentCol)
{
int i;
int curRow = currentRow;
int curCol = currentCol;
int preRow, preCol;
for (i = 0; i < curRow; i++)
{
preRow = i;
preCol = pos[i];
if (curCol == preCol || abs(currentRow - preRow) == abs(currentCol - preCol))
{
return false;
}
}
return true;
}
int sum = 0;
void getPosition(int row, int pos[N])
{
int i;
for (i = 0; i < N; i++)
{
if (workPosition(pos,row, i))
{
pos[row] = i;
if (row == N-1)
{
sum++;
cout<<"------------"<<sum<<"--------------"<<endl;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (j == pos[i])
{
cout<<" x ";
}
else
cout<<" o ";
}
cout<<endl;
}
}
else
{
getPosition(row + 1, pos);
}
}
}
}
int main()
{
int position[N] = {0};
getPosition(0, position);
cout<<sum<<endl;
}
PS1:在鑫妹JAVA版的基础上,写的C++版本。递归用的还不是很得心应手啊。
PS2:若不想讲sum放到全局变量里面,可以运用传引用。将函数设定为:
void getPosition(int row, int pos[N], int& sum)