From 6f70b15c57286fd4acb47c6c47c62a13b1c469b0 Mon Sep 17 00:00:00 2001 From: linlihong <747682928@qq.com> Date: Fri, 13 Sep 2024 11:01:18 +0800 Subject: [PATCH] =?UTF-8?q?2024/9/13=20Hot100=20=E5=9B=9E=E6=BA=AF=20?= =?UTF-8?q?=E6=9C=80=E5=90=8E=E4=B8=80=E9=A2=98n=E7=9A=87=E5=90=8E?= =?UTF-8?q?=EF=BC=8C=E6=98=A8=E6=97=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/cool/hot100/backtracking/Num51.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/main/java/com/cool/hot100/backtracking/Num51.java diff --git a/src/main/java/com/cool/hot100/backtracking/Num51.java b/src/main/java/com/cool/hot100/backtracking/Num51.java new file mode 100644 index 0000000..d8579cb --- /dev/null +++ b/src/main/java/com/cool/hot100/backtracking/Num51.java @@ -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> res = new ArrayList<>(); + + public List> 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 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); + } +}