{
  "type": "code_options",
  "author": "https://github.com/qiyuangong/leetcode",
  "source": "solution.md",
  "exercise_id": "9827e15bed994daf9516416d5163b404",
  "keywords": "数组,回溯",
  "title": "N 皇后",
  "desc": [
    {
      "content": "\n<p><strong>n 皇后问题</strong> 研究的是如何将 <code>n</code> 个皇后放置在 <code>n×n</code> 的棋盘上，并且使皇后彼此之间不能相互攻击。</p><p>给你一个整数 <code>n</code> ，返回所有不同的 <strong>n<em> </em>皇后问题</strong> 的解决方案。</p><div class=\"original__bRMd\"><div><p>每一种解法包含一个不同的 <strong>n 皇后问题</strong> 的棋子放置方案，该方案中 <code>'Q'</code> 和 <code>'.'</code> 分别代表了皇后和空位。</p><p> </p><p><strong>示例 1：</strong></p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/queens.jpg\" style=\"width: 600px; height: 268px;\" /><pre><strong>输入：</strong>n = 4<strong><br />输出：</strong>[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]<strong><br />解释：</strong>如上图所示，4 皇后问题存在两个不同的解法。</pre><p><strong>示例 2：</strong></p><pre><strong>输入：</strong>n = 1<strong><br />输出：</strong>[[\"Q\"]]</pre><p> </p><p><strong>提示：</strong></p><ul>\t<li><code>1 <= n <= 9</code></li>\t<li>皇后彼此不能相互攻击，也就是说：任何两个皇后都不能处于同一条横行、纵行或斜线上。</li></ul></div></div>",
      "language": "markdown"
    }
  ],
  "answer": [
    {
      "content": "",
      "language": "python"
    }
  ],
  "prepared": [
    [
      {
        "content": "",
        "language": "python"
      }
    ],
    [
      {
        "content": "",
        "language": "python"
      }
    ],
    [
      {
        "content": "",
        "language": "python"
      }
    ]
  ],
  "template": {
    "content": "class Solution(object):\n\tdef solveNQueens(self, n):\n\t\tif n == 0:\n\t\t\treturn 0\n\t\tres = []\n\t\tboard = [['.'] * n for t in range(n)]\n\t\tself.do_solveNQueens(res, board, n)\n\t\treturn res\n\tdef do_solveNQueens(self, res, board, num):\n\t\tif num == 0:\n\t\t\tres.append([''.join(t) for t in board])\n\t\t\treturn\n\t\tls = len(board)\n\t\tpos = ls - num\n\t\tcheck = [True] * ls\n\t\tfor i in range(pos):\n\t\t\tfor j in range(ls):\n\t\t\t\tif board[i][j] == 'Q':\n\t\t\t\t\tcheck[j] = False\n\t\t\t\t\tstep = pos - i\n\t\t\t\t\tif j + step < ls:\n\t\t\t\t\t\tcheck[j + step] = False\n\t\t\t\t\tif j - step >= 0:\n\t\t\t\t\t\tcheck[j - step] = False\n\t\t\t\t\tbreak\n\t\tfor j in range(ls):\n\t\t\tif check[j]:\n\t\t\t\tboard[pos][j] = 'Q'\n\t\t\t\tself.do_solveNQueens(res, board, num - 1)\n\t\t\t\tboard[pos][j] = '.'\nif __name__ == '__main__':\n\ts = Solution()\n\tprint (s.solveNQueens(4))",
    "language": "python"
  },
  "node_id": "dailycode-e6620e8ed01649a5b82d5c3f59a366b7",
  "license": "csdn.net",
  "created_at": 1637894160,
  "topic_link": "https://bbs.csdn.net/topics/600470831"
}