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中用的引用表示对象,要留意对引用的修改
  1. ArrayList<Integer> row = new ArrayList<Integer>();
  2. ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
  3. boolean isOk(int k,int i) {  //判断当前行的第i列是否可以放置
  4. for(int j=0;j<k;j++) {
  5. if(row.get(j) == i || Math.abs(row.get(j) - i) == Math.abs(j-k)) {
  6. return false;
  7. }
  8. }
  9. return true;
  10. }
  11. void solve(int n,int k) {
  12. if(k==n) {
  13. ArrayList<String> cur = new ArrayList<String>();  // cur表示当前方案的数组
  14. for(int i=0;i<n;i++) {
  15. StringBuffer tmp = new StringBuffer();
  16. for(int j=0;j<n;j++) {
  17. if(row.get(i)==j) {
  18. tmp.append('Q');
  19. } else {
  20. tmp.append('.');
  21. }
  22. }
  23. cur.add(tmp.toString());
  24. }
  25. res.add(cur);
  26. }
  27. for(int i=0;i<n;i++) {
  28. if(isOk(k,i)) {
  29. row.add(i);
  30. solve(n,k+1);  // DFS的思想求解
  31. row.remove(row.size()-1);
  32. }
  33. }
  34. }
  35. public ArrayList<ArrayList<String>> solveNQueens(int n) {
  36. if(n==0) return res;
  37. solve(n,0);
  38. return res;
  39. }

C++代码: 个人感觉C++中对vector、string等容器的初始化相对于java而言更加方便,如string tmp(n,'.') vector<int> tmp(n,1) 

本例中用row和col表示每行存储的列序号和已经存储的列序号~

  1. vector<vector<string> > res;
  2. int row[1000];
  3. int col[1000];
  4. void dfs(int l ,int n) {
  5. if(l==n) {
  6. vector<string> cur;
  7. for(int k=0;k<n;k++) {
  8. string tmp(n,'.');
  9. tmp[row[k]]='Q';
  10. cur.push_back(tmp);
  11. }
  12. res.push_back(cur);
  13. return;
  14. }
  15. int i=0;
  16. int j=0;
  17. for(i=0;i<n;i++) {
  18. if(col[i]==0) {
  19. for(j=0;j<l;j++)
  20. if(abs(j-l)==abs(i-row[j])) break;
  21. if(j==l) {
  22. col[i]=1;
  23. row[l]=i;
  24. dfs(l+1,n);
  25. col[i]=0;
  26. row[l]=0;
  27. }
  28. }
  29. }
  30. }
  31. vector<vector<string> > solveNQueens(int n) {
  32. res.clear();
  33. dfs(0,n);
  34. return res;
  35. }

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

思路:修改一下输出结果即可。但应该还有更好的方法,后续研究。

if(k>=n) {
sum++;
}

posted @ 2014-06-29 11:50  purejade  阅读(70)  评论(0)    收藏  举报