N-Queens

模拟退火不会写 0.0

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

回溯法(backtracking) 题目整理--------part2

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.."]
]

回溯法,刚开始思路,做一个2层的循环,后来发现其实每行之需要记录一个值,也就是queen的位置就行了。

先生成result strings(只包含queen位置的string), 然后把strings写成n-queue形式。

对于是否valid,写一个isvalid function. 做2个判断,1 同列是否冲突, 2 对角线是否冲突

代码:

 1 public class Solution {
 2     public List<List<String>> solveNQueens(int n) {
 3         List<List<String>> res = new ArrayList<List<String>>();
 4         if (n <= 0) {
 5             return res;
 6         }
 7         List<String> path = new ArrayList<String>();
 8         int[] row = new int[n];
 9         helper (res, row,  n, 0);
10         return res;
11     }
12      private void helper(List<List<String>> resultList,
13                               int[] row,
14                               int n,
15                               int index) {
16         if (n == index) {
17             ArrayList<String> singleResult = translateString(row);
18             resultList.add(singleResult);
19             return;
20         }
21        
22         for (int i = 0; i < n; i++) {
23                 if (isValid(row, index, i)) {
24                 row[index] = i;
25                 helper (resultList, row, n, index + 1);
26                 row[index] = 0;
27             }
28         }
29         
30     }
31     
32     private ArrayList<String> translateString(int[] row) {
33         ArrayList<String> resultList = new ArrayList<>();
34         for (int i = 0; i < row.length; i++) {
35             StringBuilder sb = new StringBuilder();
36             for (int j = 0; j < row.length; j++) {
37                 if (j == row[i]) {
38                     sb.append('Q');
39                 }
40                 else {
41                     sb.append('.');
42                 }
43             }
44             resultList.add(sb.toString());
45         }
46         return resultList;
47     }
48     
49     private boolean isValid(int[] row, int rowNum, int columnNum) {
50         for (int i = 0; i < rowNum; i++) {
51             if (row[i] == columnNum) {
52                 return false;
53             }
54             //对角线检查
55             if (Math.abs(row[i] - columnNum) == Math.abs(i - rowNum)) {
56                 return false;
57             }
58         }
59         return true;
60     }
61 }
n-queens

相关文章: