N-Queens

Then-queens puzzle is the problem of placingnqueens on ann×nchessboard such that no two queens attack each other.

Given an integern, return all distinct solutions to then-queens puzzle.

Each solution contains a distinct board configuration of then-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:

分析

结论

图形
适用公式
说明

正方形

abs(Δrow) == abs(Δcol)

对角线行差和列差绝对值相等

长方形

Δrow / Δcol == ±(height/width)

需按长宽比例判断

这是一个回溯法解决N皇后问题的代码。

  • 棋盘表示:用 List<String> 表示一个棋盘,每个 String 是一行的布局(如 "Q... 表示皇后在第1列)。

  • 核心思路

    1. cols 记录每行皇后的列位置(如 [1,3,0,2] 表示第0行放第1列,第1行放第3列等)。

    2. DFS逐行放置:每层递归处理一行,尝试所有可能的列位置,通过 isValid 检查是否冲突(列、对角线)。

    3. 终止条件:当 row 填满(cols.size() == n),生成棋盘并加入结果。

关键点:

  • cols 直接存储每行皇后的列下标(如 [2,0,3,1]),而非二维数组。

  • 验证冲突:只需检查当前列是否已被占用,或与之前皇后是否在同一对角线(|row1 - row2| == |col1 - col2|)。

  • 效率:通过回溯剪枝,避免无效尝试。

示例:

对于4皇后问题,一个合法解 cols = [1,3,0,2] 对应的棋盘:

Last updated

Was this helpful?