首页 > 代码库 > 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.."]
]

N皇后问题,回溯法DFS做,做法比较简单,直接贴代码:

 1 public ArrayList<String[]> solveNQueens(int n) {
 2         ArrayList<String[]> result = new ArrayList<String[]>();
 3         int pos[] = new int[n];
 4         for (int i = 0; i < pos.length; i++) {
 5             pos[i] = -1;
 6         }
 7         solve(pos, 0, n, result);
 8         return result;
 9     }
10 
11     private void solve(int[] pos, int p, int n, ArrayList<String[]> result) {
12         // TODO Auto-generated method stub
13         if (p >= n) {
14             parse(pos, result, n);
15             return;
16         }
17         for (int i = 0; i < n; i++) {
18             int j = 0;
19             int temp[] = pos.clone();
20             for (; j < n; j++) {
21                 if (temp[j] == i
22                         || (temp[j] >= 0 && Math.abs(temp[j] - i) == Math.abs(p
23                                 - j))) {
24                     break;
25                 }
26             }
27             if (j == n) {
28                 temp[p] = i;
29                 solve(temp, p + 1, n, result);
30             }
31         }
32     }
33 
34     private void parse(int[] pos, ArrayList<String[]> result, int n) {
35         // TODO Auto-generated method stub
36         String temp[] = new String[n];
37         for (int i = 0; i < n; i++) {
38             String t = "";
39             for (int j = 0; j < n; j++) {
40                 if (pos[i] == j) {
41                     t += "Q";
42                 } else {
43                     t += ".";
44                 }
45             }
46             temp[i] = t;
47         }
48         result.add(temp);
49     }

整体复杂度应该是O(N^2)吧

遇到的问题是java参数传递,int数组在传递过程中是什么传递方式?

引用网上的话说就是:

基本类型作为参数传递时,是传递值的拷贝,无论你怎么改变这个拷贝,原值是不会改变的

Java中对象作为参数传递时,是把对象在内存中的地址拷贝了一份传给了参数

 

那么数组作为参数传递呢?

public static void change(int[] p){
  p[0] = 1;
}

这样一个函数中,如果这样调用:

int p[] = {0,0,0};
for(int i:p){
  System.out.print(i+" ");
}
System.out.println();
change(p);
for(int i:p){
  System.out.print(i+" ");
}

输出为:

0,0,0

1,0,0

可以看出,结果更改了,说明基本类型的数组作为参数传递时参照对象作为参数传递的方式