在8*8的棋盘上摆8个皇后,使任2皇后不在同一行、列、对角线上,有几种摆法?
可以扩展到N皇后。
#include <iostream>
#include <string>
using namespace std;
#define NUM 8
char cache[NUM][NUM] = {0};
void queen(int row, int max)
{
// 依次放置在列上
for (int i = 0; i < max; ++i)
{
// 清空当前行
memset(cache[row], 'x', max);
bool fHas = false;
// 判断同一列
for(int irow = 0; irow < row; ++irow)
{
if(cache[irow][i] == 'o')
{
fHas = true;
break;
}
// 对角线是否有皇后
int icol = i;
if(icol + (row - irow) < max)
{
if(cache[irow][icol + (row - irow)] == 'o')
{
fHas = true;
break;
}
}
if(icol - (row - irow) >= 0)
{
if(cache[irow][icol - (row - irow)] == 'o')
{
fHas = true;
break;
}
}
}
if(fHas)
continue;
cache[row][i] = 'o';
if(row < max - 1)
queen(row + 1, max);
if(row == max - 1)
{
for (int i = 0; i < max; ++i)
{
for (int j = 0; j < max; ++j)
{
cout<< cache[i][j]<< " ";
}
cout<< endl;
}
cout<< endl;
}
}
}
int main(int argc, char* argv[])
{
queen(0, NUM);
return 0;
}
#include <string>
using namespace std;
#define NUM 8
char cache[NUM][NUM] = {0};
void queen(int row, int max)
{
// 依次放置在列上
for (int i = 0; i < max; ++i)
{
// 清空当前行
memset(cache[row], 'x', max);
bool fHas = false;
// 判断同一列
for(int irow = 0; irow < row; ++irow)
{
if(cache[irow][i] == 'o')
{
fHas = true;
break;
}
// 对角线是否有皇后
int icol = i;
if(icol + (row - irow) < max)
{
if(cache[irow][icol + (row - irow)] == 'o')
{
fHas = true;
break;
}
}
if(icol - (row - irow) >= 0)
{
if(cache[irow][icol - (row - irow)] == 'o')
{
fHas = true;
break;
}
}
}
if(fHas)
continue;
cache[row][i] = 'o';
if(row < max - 1)
queen(row + 1, max);
if(row == max - 1)
{
for (int i = 0; i < max; ++i)
{
for (int j = 0; j < max; ++j)
{
cout<< cache[i][j]<< " ";
}
cout<< endl;
}
cout<< endl;
}
}
}
int main(int argc, char* argv[])
{
queen(0, NUM);
return 0;
}