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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。