标签:
题目:
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.."] ]
思路: 这题就像上篇我们做的palindrome partition是一个类型的。等着把这类题写在一起做个对比。先直接上代码:
1 public List<String[]> solveNQueens(int n) { 2 List<String[]> ret = new ArrayList<String[]>(); 3 if (n == 0) { 4 return ret; 5 } 6 helper(n, 0, new int[n], ret); 7 return ret; 8 } 9 10 private static void helper(int n, int row, int[] marked, List<String[]> ret) { 11 if (row == n) { 12 String[] subRet = new String[n]; 13 for (int i = 0; i < n; i++) { 14 StringBuilder str = new StringBuilder(); 15 for (int j = 0; j < n; j++) { 16 if (marked[i] == j) { 17 str.append(‘Q‘); 18 }else{ 19 str.append(‘.‘); 20 } 21 } 22 subRet[i] = str.toString(); 23 } 24 ret.add(subRet); 25 //forget to return; 26 return; 27 } 28 for (int i = 0; i < n; i++) { 29 marked[row] = i 30 if (isValid(row, marked)) { 31 helper(n, row + 1, marked, ret); 32 } 33 } 34 } 35 36 private static boolean isValid(int row, int[] marked) { 37 for (int i = 0; i < row; i++) { 38 if (marked[row] == marked[i] || Math.abs(marked[row] - marked[i]) = ) 39 } 40 }
标签:
原文地址:http://www.cnblogs.com/gonuts/p/4470277.html