【LeetCode】 51. N-Queens N皇后(Hard)(JAVA)
Topic Address: https://leetcode.com/problems/n-queens/
Subject description:
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.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
Subject to the effect
N-queens problem is to study how the n-queens placed on an n × n chessboard, and the queen can not attack each other to each other.
Problem-solving approach
1, n queens problem: vertical, diagonal can not have the same presence of
two by three arrays are recorded, column, column + Row, Row - column
. 3, the results obtained recursively
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
List<String> cur = new ArrayList<>();
int[] col = new int[n];
int[] rowPcol = new int[2 * n];
int[] rowMcol = new int[2 * n];
sH(res, cur, col, rowPcol, rowMcol, n);
return res;
}
public void sH(List<List<String>> res, List<String> cur, int[] col, int[] rowPcol, int[] rowMcol, int n) {
int row = cur.size();
if (row >= n) {
res.add(new ArrayList<>(cur));
return;
}
for (int i = 0; i < n; i++) {
if (col[i] > 0 || rowPcol[i + row] > 0 || rowMcol[row - i + n] > 0) continue;
col[i] = 1;
rowPcol[i + row] = 1;
rowMcol[row - i + n] = 1;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
if (i == j) {
sb.append('Q');
} else {
sb.append('.');
}
}
cur.add(sb.toString());
sH(res, cur, col, rowPcol, rowMcol, n);
col[i] = 0;
rowPcol[i + row] = 0;
rowMcol[row - i + n] = 0;
cur.remove(cur.size() - 1);
}
}
}
When execution: 3 ms, beat the 90.76% of all users to submit in Java
memory consumption: 42.1 MB, beat the 5.09% of all users to submit in Java