2024/9/13 Hot100 回溯 最后一题n皇后,昨日

This commit is contained in:
linlihong 2024-09-13 11:01:18 +08:00
parent ca680d7b82
commit 6f70b15c57
1 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,65 @@
package com.cool.hot100.backtracking;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/13/09:50
* DayNumber 1
* Hard 3
* Level 6
*/
public class Num51 {
char[][] chars;
boolean[] xBool;
boolean[] dir1;
boolean[] dir2;
int n;
List<List<String>> res = new ArrayList<>();
public List<List<String>> solveNQueens(int n) {
this.n = n;
chars = new char[n][n];
xBool = new boolean[n];
dir1 = new boolean[2 * n];
dir2 = new boolean[2 * n];
for (int i = 0; i < n; i++) {
Arrays.fill(chars[i], '.');
}
dfs(0);
return res;
}
private void dfs(int y) {
if (y >= n) {
List<String> list = new ArrayList<>();
for (char[] cs : chars) {
list.add(new String(cs));
}
res.add(list);
return;
}
for (int x = 0; x < n; x++) {
if (xBool[x] || dir1[x + y] || dir2[x - y + n]) {
continue;
}
xBool[x] = dir1[x + y] = dir2[x - y + n] = true;
chars[x][y] = 'Q';
dfs(y + 1);
xBool[x] = dir1[x + y] = dir2[x - y + n] = false;
chars[x][y] = '.';
}
}
@Test
public void test() {
solveNQueens(4);
}
}