The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-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:[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."]] 解题思路:经典N皇后问题,代码主要参照晴神宝典103页,P[index]=x表示第index行皇后的位置为x,hashTable[x]=True表示第x行已经有皇后放置了,对角线判断用了绝对值 简化了本来的算法
class Solution {public: vector>ans; bool hashTable[100]={ false}; int P[100]={ 0}; void generateP(int index,int n){ if(index==n+1){ string temp=""; vector tempAns; for(int i=1;i<=n;i++){ temp=""; for(int j=1;j<=n;j++) temp+='.'; temp[P[i]-1]='Q'; // cout< < > solveNQueens(int n) { generateP(1,n); return ans; }};