g0001_0100.s0051_n_queens.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0051_n_queens;
// #Hard #Array #Backtracking #2022_02_19_Time_3_ms_(87.94%)_Space_45.5_MB_(21.87%)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public List> solveNQueens(int n) {
boolean[] pos = new boolean[n + 2 * n - 1 + 2 * n - 1];
int[] pos2 = new int[n];
List> ans = new ArrayList<>();
helper(n, 0, pos, pos2, ans);
return ans;
}
private void helper(int n, int row, boolean[] pos, int[] pos2, List> ans) {
if (row == n) {
construct(n, pos2, ans);
return;
}
for (int i = 0; i < n; i++) {
int index = n + 2 * n - 1 + n - 1 + i - row;
if (pos[i] || pos[n + i + row] || pos[index]) {
continue;
}
pos[i] = true;
pos[n + i + row] = true;
pos[index] = true;
pos2[row] = i;
helper(n, row + 1, pos, pos2, ans);
pos[i] = false;
pos[n + i + row] = false;
pos[index] = false;
}
}
private void construct(int n, int[] pos, List> ans) {
List sol = new ArrayList<>();
for (int r = 0; r < n; r++) {
char[] queenRow = new char[n];
Arrays.fill(queenRow, '.');
queenRow[pos[r]] = 'Q';
sol.add(new String(queenRow));
}
ans.add(sol);
}
}