# 51. N-Queens

The n-queens puzzle is the problem of placing n queens on ann×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.."]
]


	static int[] col;
static List<List<String>> res;

public static List<List<String>> solveNQueens(int n) {
res = new ArrayList<List<String>>();
col = new int[n];
nqueens(0, n);
return res;
}

public static void nqueens(int colIndex, int n) {
if (colIndex == n) {
printRes(n);
return;
}
for (int i = 0; i < n; i++) {
col[colIndex] = i;
if (valid(colIndex)) {
nqueens(colIndex + 1, n);
}
}
}

private static boolean valid(int colIndex) {
for (int i = 0; i < colIndex; i++) {
// 行不可能重复，列如果重复或者对角线重复
if (col[i] == col[colIndex]
|| Math.abs(col[i] - col[colIndex]) == colIndex - i) {
return false;
}
}
return true;
}

private static void printRes(int n) {
List<String> resList = new ArrayList<String>();
for (int i = 0; i < n; i++) {
StringBuffer buffer = new StringBuffer();
int tmp = col[i];
for (int j = 0; j < tmp; j++) {
buffer.append(".");
}
buffer.append("Q");
for (int j = tmp + 1; j < n; j++) {
buffer.append(".");
}
}
}

• 本文已收录于以下专栏：

## 【LeetCode】51. N-Queens

51. N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that...

## [Leetcode 51, hard] N-Queens I

[Leetcode 51 & 52, hard] N-Queens I

## LeetCode-51. N-Queens (JAVA)（打印N皇后解集）

LeetCode-51. N-Queens (JAVA)（打印N皇后解集）

## Leetcode 51. N-Queens

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

## LeetCode51:N-Queens

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

## LeetCode 51. N-Queens

Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contain...
• liuchuo
• 2016年07月22日 00:29
• 119

## LeetCode-51&52.N-Queens

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

## LeetCode --- 51. N-Queens

• makuiyu
• 2015年03月07日 10:46
• 1372

## LeetCode 51 N-Queens II

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe...

## leetcode(51):N-Queens

【原题】 The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two q...

举报原因： 您举报文章：51. N-Queens 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)