leetcode:N-Queens (n皇后問題) 【面試演算法題】
阿新 • • 發佈:2019-02-03
題目: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皇后問題,題意就是求n×n矩陣中,每行放一個棋子,使得棋子所在的列和兩條斜線上沒有其他棋子,列舉所有可能。
dfs去遍歷,考慮所有可能,row中記錄每一行棋子的位置,col記錄當前列是否有棋子,對角線的判斷就是兩點行差值和列差值是否相同。
當dfs深度達到n時,就表示存在滿足條件的解,把當前狀態圖存到結果中。
temp(n, '.')先把字串全部賦值成 ‘ . ' ,在吧存在棋子的位置改成’Q‘
int row[1000]; int col[1000]; vector<vector<string> >result; class Solution { public: void dfs(int r,int n) { int i,j; if(r==n) { vector<string>go; for(i=0;i<n;++i) { string temp(n,'.'); temp[row[i]]='Q'; go.push_back(temp); } result.push_back(go); } for(i=0;i<n;++i) { if(col[i]==0) { for(j=0;j<r;++j) if(abs(j-r)==abs(i-row[j]))break; if(j==r) { row[r]=i; col[i]=1; dfs(r+1,n); col[i]=0; row[r]=0; } } } } vector<vector<string> > solveNQueens(int n) { result.clear(); dfs(0,n); return result; } }; // blog.csdn.net/havenoidea