51. N-Queens
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<vector<string> >ans; bool hashTable[100]={false}; int P[100]={0}; void generateP(int index,int n){ if(index==n+1){ string temp=""; vector<string>tempAns; for(int i=1;i<=n;i++){ temp=""; for(int j=1;j<=n;j++) temp+='.'; temp[P[i]-1]='Q'; // cout<<temp<<endl; tempAns.push_back(temp); } ans.push_back(tempAns); return ; } for(int x=1;x<=n;x++){ if(hashTable[x]==false){ bool flag=true; for(int pre=1;pre<index;pre++){ if(abs(index-pre)==abs(x-P[pre])){ flag=false; break; } } if(flag){ P[index]=x; hashTable[x]=true; generateP(index+1,n); hashTable[x]=false; } } } } vector<vector<string>> solveNQueens(int n) { generateP(1,n); return ans; } };