八皇后问题,即八个皇后放在8*8的格子上,要求每个皇后不同行、不同列,也不再对角线上。
解法一:全排列解法。八个皇后不同行,那么假设存在一个数组大小为8,数组下标代表行,0~7都会被占满,数组每个下标位置上的值代表当前皇后的列,即下标值代表皇后的行,数组值代表列。下标0~7肯定会不同,如果以0~7初始化数组,那么列也会完全不同。那么列的排列就是0~7八个数的全排列问题,剩下的就是要判断是不是在对角线上了,具体代码实现见:http://blog.youkuaiyun.com/moses1213/article/details/51055692
解法二:也是设一个长度为8的数组,对数组每个位置上的值即列的值都进行判断,如果合法则放上去,即每个下标都放上0~7,直到数组每个位置上都放上了合法的值。
#include <iostream>
#include <math.h>
using namespace std;
#define GRID_SIZE 8
bool CheckValid(int* column, int row, int col)
{
for(int beforeRow = 0; beforeRow < row; ++beforeRow)
{
if(column[beforeRow] == col)
return false;
int columnDistance = abs(column[beforeRow]-col);
int rowDistance = row - beforeRow;
if(columnDistance == rowDistance)
return false;
}
return true;
}
void PlaceQueen(int* column, int row)
{
static int count = 0;
if(row == GRID_SIZE)
{
++count;
cout << "第" << count << "种解法:";
for(int i = 0; i < GRID_SIZE; ++i)
{
cout << column[i] << " ";
if(i == 7)
cout << endl;
}
}
else
{
for(int col = 0; col < GRID_SIZE; ++col)
{
if(CheckValid(column, row, col))
{
column[row] = col;
PlaceQueen(column, row+1);
}
}
}
}
void Queen8()
{
int column[8];
PlaceQueen(column, 0);
}
int main() {
// your code goes here
Queen8();
return 0;
}