码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-10-06 06:59:07      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

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.

技术分享

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

 

--------------------------我是分割线-------------------

N-Queens II

Follow up for N-Queens problem.

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

技术分享

 

 注意建立的res 是静态变量,在主方法里面赋值,防止它是dirty的

技术分享
 1 public class Solution {
 2     static int res;
 3     public int totalNQueens(int n) {
 4         if (n <= 0) {
 5             return 0;
 6         }
 7         int[] rows = new int[n];
 8         int index = 0;
 9         res = 0;
10         helper(0, rows);
11         return res;
12         
13     }
14     
15     private static void helper(int index,  int[] rows) {
16         int n = rows.length;
17         if (index == n) {
18             res++;
19             return;
20         }
21         for (int i = 0; i < n; i++) {
22             if (isValid(rows, index, i)) {
23                 rows[index] = i;
24                 helper(index + 1,  rows);
25             }
26         }
27     }
28     
29     private static boolean isValid(int rows[], int rowNum, int columnNum) {
30         for (int i = 0; i < rowNum; i++) {
31                 if (rows[i] == columnNum) {
32                     return false;
33                 }
34                 if (Math.abs(rows[i] - columnNum) == Math.abs(i - rowNum)) {
35                     //columnNum1 - columnNum2 = rowNum1 - rowNum2 平行!
36                     return false;
37                 }
38             }
39         return true;
40     }
41 }
totalNQueens

 

 

 

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

标签:

原文地址:http://www.cnblogs.com/jiangchen/p/5931754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!