首页 > 代码库 > N-Queens
N-Queens
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.."]]
思路:主要思想就是一句话:用一个循环递归处理子问题。这个问题中,在每一层递归函数中,我们用一个循环把一个皇后填入对应行的某一列中,如果当前棋盘合法,我们就递归处理先一行,找到正确的棋盘我们就存储到结果集里面。
这种题目都是使用这个套路,就是用一个循环去枚举当前所有情况,然后把元素加入,递归,再把元素移除,这道题目中不用移除的原因是我们用一个一维数组去存皇后在对应行的哪一列,因为一行只能有一个皇后,如果二维数组,那么就需要把那一行那一列在递归结束后设回没有皇后,所以道理是一样的。
参考:http://www.cnblogs.com/TenosDoIt/p/3801621.html
C++实现代码:
#include<iostream>#include<vector>#include<string>using namespace std;class Solution {public: vector<vector<string> > solveNQueens(int n) { vector<vector<string> > res; vector<string> path(n,string(n,‘.‘)); helper(n,0,res,path); return res; } void helper(int n,int start,vector<vector<string> > &res,vector<string> &path) { if(start==n) { res.push_back(path); return; } int i; //i用来设置每一列,start代表每一行 for(i=0;i<n;i++) { if(isValid(path,start,i)) { path[start][i]=‘Q‘; helper(n,start+1,res,path); path[start][i]=‘.‘; } } } bool isValid(vector<string> &path,int row,int col) { int i,j; for(i=0;i<row;i++) if(path[i][col]==‘Q‘) return false; for(i=row-1,j=col-1;i>=0&&j>=0;i--,j--) if(path[i][j]==‘Q‘) return false; for(i=row-1,j=col+1;i>=0&&j<(int)path.size();i--,j++) if(path[i][j]==‘Q‘) return false; return true; }};int main(){ Solution s; vector<vector<string> > result=s.solveNQueens(4); for(auto a:result) { for(auto v:a) cout<<v<<endl; cout<<endl; }}
运行结果:
N-Queens