N-Queens & N-Queens II
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.."] ]
思想: 用DFS的思想遍历即可,注意中间结果的保存,在java中用的引用表示对象,要留意对引用的修改
- ArrayList<Integer> row = new ArrayList<Integer>();
- ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
- boolean isOk(int k,int i) { //判断当前行的第i列是否可以放置
- for(int j=0;j<k;j++) {
- if(row.get(j) == i || Math.abs(row.get(j) - i) == Math.abs(j-k)) {
- return false;
- }
- }
- return true;
- }
- void solve(int n,int k) {
- if(k==n) {
- ArrayList<String> cur = new ArrayList<String>(); // cur表示当前方案的数组
- for(int i=0;i<n;i++) {
- StringBuffer tmp = new StringBuffer();
- for(int j=0;j<n;j++) {
- if(row.get(i)==j) {
- tmp.append('Q');
- } else {
- tmp.append('.');
- }
- }
- cur.add(tmp.toString());
- }
- res.add(cur);
- }
- for(int i=0;i<n;i++) {
- if(isOk(k,i)) {
- row.add(i);
- solve(n,k+1); // DFS的思想求解
- row.remove(row.size()-1);
- }
- }
- }
- public ArrayList<ArrayList<String>> solveNQueens(int n) {
- if(n==0) return res;
- solve(n,0);
- return res;
- }
C++代码: 个人感觉C++中对vector、string等容器的初始化相对于java而言更加方便,如string tmp(n,'.') vector<int> tmp(n,1)
本例中用row和col表示每行存储的列序号和已经存储的列序号~
- vector<vector<string> > res;
- int row[1000];
- int col[1000];
- void dfs(int l ,int n) {
- if(l==n) {
- vector<string> cur;
- for(int k=0;k<n;k++) {
- string tmp(n,'.');
- tmp[row[k]]='Q';
- cur.push_back(tmp);
- }
- res.push_back(cur);
- return;
- }
- int i=0;
- int j=0;
- for(i=0;i<n;i++) {
- if(col[i]==0) {
- for(j=0;j<l;j++)
- if(abs(j-l)==abs(i-row[j])) break;
- if(j==l) {
- col[i]=1;
- row[l]=i;
- dfs(l+1,n);
- col[i]=0;
- row[l]=0;
- }
- }
- }
- }
- vector<vector<string> > solveNQueens(int n) {
- res.clear();
- dfs(0,n);
- return res;
- }
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
思路:修改一下输出结果即可。但应该还有更好的方法,后续研究。
if(k>=n) {
sum++;
}

浙公网安备 33010602011771号