from : https://leetcode.com/problems/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.."] ]
思路 :
回溯,用一个char数组queue存放已经排好的皇后的位置,然后寻找新的位置。
public class Solution {
private List<List<String>> solutions;
private char[] dots;
public List<List<String>> solveNQueens(int n) {
init(n);
int[] queue = new int[n];
// queue[i]=k means the ith line and kth column has the Queue
traverse(queue, 0, n);
return solutions;
}
private void traverse(int[] queue, int k, int n) {
if(k == n) {
generate(queue);
}
for(int i=0; i<n; ++i) {
boolean valid = true;
for(int j=0; j<k; ++j) {
if(i == queue[j] || Math.abs(queue[j]-i) == k-j) {
// if same column of diagonal
valid = false;
break;
}
}
if(valid) {
queue[k] = i;
traverse(queue, k+1, n);
}
}
}
private void generate(int[] queue) {
List<String> q = new ArrayList<String>();
for(int i=0, len = queue.length; i<len; ++i) {
int idx = queue[i];
dots[idx] = 'Q';
q.add(new String(dots));
dots[idx] = '.';
}
solutions.add(q);
}
private void init(int n) {
solutions = new ArrayList<List<String>>();
dots = new char[n];
for(int i=0; i<n; ++i) {
dots[i] = '.';
}
}
}
public class Solution {
private List<List<String>> ans = null;
private int N = 0;
private int[] position = null;
private char[] dots = null;
public List<List<String>> solveNQueens(int n) {
if (n < 1) {
return new ArrayList<List<String>>();
}
init(n);
takeRow(0);
return ans;
}
private void takeRow(int k) {
if (k == N) {
addToAns();
return;
}
for (int j = 0; j < N; ++j) {
boolean valid = true;
for (int i = 0; i < k && valid; ++i) {
if (position[i] == j || Math.abs(position[i] - j) == k - i) {
valid = false;
}
}
if (valid) {
position[k] = j;
takeRow(k + 1);
}
}
}
private void addToAns() {
List<String> one = new ArrayList<String>();
for (int i = 0; i < N; ++i) {
int j = position[i];
dots[j] = 'Q';
one.add(new String(dots));
dots[j] = '.';
}
ans.add(one);
}
private void init(int n) {
N = n;
ans = new ArrayList<List<String>>();
position = new int[n];
dots = new char[n];
Arrays.fill(dots, '.');
}
}