The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]n皇后是很经典的问题,对于练习枚举是很好的例子。
基本概念介绍详见:回溯法---n皇后问题
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool meet_condition(vector<int> &res_one,int level,int cloumn);
void solveNQueens(int n,int level,vector<int> &res_one,vector<vector<string>> &res_str);
vector<vector<string> > solveNQueens(int n);
int main()
{
int n;
cin>>n;
vector<vector<string>> res_str;
res_str = solveNQueens(n);
for(int i = 0;i < res_str.size();i++)
{
for(int j = 0;j < res_str[i].size();j++)
{
cout<<res_str[i][j]<<endl;
}
cout<<endl;
}
return 0;
}
vector<vector<string> > solveNQueens(int n)
{
vector<int> res_one(n,-1);
vector<vector<string>> res_str;
solveNQueens(n,0,res_one,res_str);
return res_str;
}
void solveNQueens(int n,int level,vector<int> &res_one,vector<vector<string>> &res_str)
{
if (level >= n)
{
vector<string> res_one_str;
for (int i = 0;i < n;i++)//处理选择的数字,转换成字符串矩阵!
{
string str;
for (int j = 0;j < n;j++)
{
if (res_one[i] == j)
{
str.push_back('Q');
}
else
{
str.push_back('.');
}
}
res_one_str.push_back(str);
}
res_str.push_back(res_one_str);
return ;
}
for (int i = 0;i < n;i++)//遍历各种情况
{
if (meet_condition(res_one,level,i))
{
res_one[level] = i;
solveNQueens(n,level+1,res_one,res_str);
}
}
}
bool meet_condition(vector<int> &res_one,int level,int cloumn)//不能同行,同列
{
for (int i = 0;i < level;i++)
{
if(cloumn == res_one[i])//同列 --- 不能同列!!
{
return false;
}
if (abs(level - i) == abs(cloumn - res_one[i]))//对角线!!
{
return false;
}
}
return true;
}