150强访谈中等

北皇后区

“N Queens”问题的详细指南和 Python 实现。

问题陈述

中等

n 皇后难题是将 n 个皇后放置在 n x n 棋盘上,使得两个皇后不会互相攻击。

给定一个整数 n,返回 n 皇后难题的所有不同解。您可以按任何顺序返回答案。

每个解决方案都包含 n 皇后位置的独特板配置,其中“Q”和“.”两者分别表示皇后和空位。

实现函数 solveNQueens(n: int) -> list

约束条件
  • 1 <= n <= 9

示例

Example 1
Input
4
Output
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...",".Q..","...Q"]]
Explanation

There are exactly 2 distinct solutions to the 4-queens puzzle.

Example 2
Input
1
Output
[["Q"]]
Explanation

A single queen on a 1x1 board is the only solution.

Need a Hint?
考虑使用回溯特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。