标签:style blog http ar io color os 使用 sp
N-Queens Total Accepted: 16418 Total Submissions: 63309 My
Submissions
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:
[
1 public class Solution { 2 public List<String[]> solveNQueens(int n) { 3 List<String[]> ret = new ArrayList<String[]>(); 4 5 if (n == 0) { 6 return ret; 7 } 8 9 dfs(n, new ArrayList<Integer>(), ret); 10 return ret; 11 } 12 13 public String[] createSolution(ArrayList<Integer> path) { 14 /* 15 [ 16 [".Q..", // Solution 1 17 "...Q", 18 "Q...", 19 "..Q."], 20 21 ["..Q.", // Solution 2 22 "Q...", 23 "...Q", 24 ".Q.."] 25 ] 26 */ 27 int size = path.size(); 28 String[] ret = new String[size]; 29 30 for (int i = 0; i< size; i++) { 31 StringBuilder sb = new StringBuilder(); 32 for (int j = 0; j < size; j++) { 33 // a queen. 34 if (j == path.get(i)) { 35 sb.append(‘Q‘); 36 } else { 37 sb.append(‘.‘); 38 } 39 } 40 41 ret[i] = sb.toString(); 42 } 43 44 return ret; 45 } 46 47 //ArrayList<Integer> path: store the index of the columns of one solution. 48 public void dfs(int n, ArrayList<Integer> path, List<String[]> ret) { 49 if (path.size() == n) { 50 String[] solution = createSolution(path); 51 ret.add(solution); 52 return; 53 } 54 55 for (int i = 0; i < n; i++) { 56 // Judge if this is a solution; 57 if (!isValid(path, i)) { 58 continue; 59 } 60 61 path.add(i); 62 dfs(n, path, ret); 63 path.remove(path.size() - 1); 64 } 65 } 66 67 public boolean isValid(ArrayList<Integer> path, int index) { 68 int size = path.size(); 69 for (int i = 0; i < size; i++) { 70 // Same column as one queen. 71 if (index == path.get(i)) { 72 return false; 73 } 74 75 // 在两条对角线之上 76 // bug 3: 少一个) 77 if (size - i == Math.abs(index - path.get(i))) { 78 return false; 79 } 80 } 81 82 return true; 83 } 84 }
步骤:
标签:style blog http ar io color os 使用 sp
原文地址:http://www.cnblogs.com/yuzhangcmu/p/4170148.html