[LeetCode#51]N-Queens
10846 단어 LeetCode
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.."]
]
My analysis:
The N-Queuens problem is a typical recursion problem with backtracking property.
The key idea:
At current row, we place the Queue at a column(often use a for loop). Then we validate this placement, if the placement is legal, we step into the next row.
1. We need to record following information during the recursion process:(pass through arguments)
1.1 the total N. this is used for base case checking.
1.2 the current row.
1.3 previous rows's placement(which column).
1.4 the final result set.
private void helper(int n, int cur_row, int[] placed_row, ArrayList<String[]> ret);
2. Check the base case.
Skill: like the base case checking we used in other rursive problem. we check the base case at the virtual layer next the last layer. The ration is that: iff we could reach the virtual layer, it indicates the current placed_row is legal in all previous layers.(which means a valid N-Queues placement!)
if (cur_row == n) { //note we start cur_row from 0, the last row is n-1.
...
}
3. The skills in backtracking.
two invalid cases:
3.1 two Queues were placed in the same column.
placed_row[cur_row] == placed_row[i]
3.2 two Queues were placed in a diagonal line.
Math.abs(placed_row[cur_row]-placed_row[i]) == cur_row-i
Note: we only check the current row's placement with that of its previous rows.
private boolean checkNotCollision(int[] placed_row, int cur_row) {
for (int i = 0; i < cur_row; i++) {
if (placed_row[cur_row] == placed_row[i] || Math.abs(placed_row[cur_row]-placed_row[i]) == cur_row-i)
return false;
}
return true;
}
4. The skills in recording the state of current placement.
One errors thinking pattern: since we need to pass the same updated state into different banches, we should copy the state at each recursion step in oder to not mess the state in other branches.
The pattern is abolutely wrong. The reason is that we continue the recursive process row by row, and we record the current row's index. At one recursion, the different branches would begin with the same state. (no matter whether other branches finish first or not, since other branches would only affect the rows after the current row(including current row)). The changed current row state could be easily recovered by:
for (int i = 0; i < n; i++) {
placed_row[cur_row] = i; //for current branch i, we see the same state(previous rows' state)
if (checkNotCollision(placed_row, cur_row)) {
helper(n, cur_row+1, placed_row, ret);
}
}
for (int i = 0; i < cur_row; i++) {
if (placed_row[cur_row] == placed_row[i] || Math.abs(placed_row[cur_row]-placed_row[i]) == cur_row-i)
return false;
}
Thus for each recursion level, we could only use one state array, because :
for (int i = 0; i < n; i++) {
placed_row[cur_row] = i;
...
}
for cross recursion level, we could also only use one state array, because:
for (int i = 0; i < cur_row; i++) {
...
}
Amazing: only one state array is enough!!!
My solution:
public class Solution {
public List<String[]> solveNQueens(int n) {
ArrayList<String[]> ret = new ArrayList<String[]> ();
if (n <= 0)
return ret;
int[] placed_row = new int[n];
helper(n, 0, placed_row, ret);
return ret;
}
private void helper(int n, int cur_row, int[] placed_row, ArrayList<String[]> ret) {
if (cur_row == n) {
String[] item = new String[n];
for (int i = 0; i < n; i++) {
StringBuffer sub_item = new StringBuffer();
for (int j = 0; j < n; j++) {
if (placed_row[i] == j)
sub_item.append('Q');
else
sub_item.append('.');
}
item[i] = sub_item.toString();
}
ret.add(item);
return;
}
for (int i = 0; i < n; i++) {
placed_row[cur_row] = i;
if (checkNotCollision(placed_row, cur_row)) {
helper(n, cur_row+1, placed_row, ret);
}
}
}
private boolean checkNotCollision(int[] placed_row, int cur_row) {
for (int i = 0; i < cur_row; i++) {
if (placed_row[cur_row] == placed_row[i] || Math.abs(placed_row[cur_row]-placed_row[i]) == cur_row-i)
return false;
}
return true;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.