n-queens(n皇后問題)
阿新 • • 發佈:2019-01-09
問題描述
The n queens puzzle is the problem of placing n queens on an N x 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
For example,
There exist two distinct solutions to the 4-queens puzzle:
題目大意
著名n皇后問題。
n個皇后擺放在N x N
的棋盤格中,使得橫、豎和兩個對角線方向均不會同時出現兩個皇后。
解題思路
n皇后問題當n大於等於4才有討論意義,而且不只有一個解決方案;
用遞迴的方法找到每一種解決方案;
在當前解決方案中,遍歷每一行的每一列查詢可以放置皇后的位置
在當前行中,遍歷每一列的每一個位置,假設當前位置可以放,然後進行合法性判斷,合法則放置;
然後再遞迴判斷下一行;
遞迴結束後,將當前行當前列的位置回溯,置為未放狀態,再接著判斷當前行下一列,目的是為了找到所有的解決方案。
程式碼
#include<iostream> #include<vector> using namespace std; /* 函式宣告 */ // 解決方案函式 vector<vector<string > > solveNQueens(int n); // 用深度優先搜尋的遞迴實現進行查詢解決方案 void dfs(vector<vector<string > > &res, vector<string > &cur, int &n, int row); // 判斷是否可以在當前的row行col列進行放置的合法性 bool isValid(vector<string> &cur, int &n, int row, int col); vector<vector<string > > solveNQueens(int n) { // 解決方案結果集 vector<vector<string > > res; // 初始化棋盤,所有的位置都沒有擺放皇后 vector<string> cur(n, string(n, '.')); dfs(res, cur, n, 0); return res; } /* res:返回的解決方案集 cur:當前的一個解決方案 n:n皇后問題 row:當前解決方案的第row行 */ void dfs(vector<vector<string > > &res, vector<string> &cur, int &n, int row) { // 當超出行數超出了棋盤,則把這次搜尋的結果放入res中。 if (row == n) { res.push_back(cur); return; } for (int j = 0; j < n; j++) { // 判斷在row行j列處是否可以放一個皇后 if (isValid(cur, n, row, j)) { // 如果可以,則放一個皇后在(row,j) cur[row][j] = 'Q'; // 繼續在下一行找一個位置放皇后 dfs(res, cur, n, row + 1); // 因為需要找到所有可能的情況,所以必然需要對每一行進行回退。 // 去判斷這一行的下一列是否可以放皇后。 cur[row][j] = '.'; } } } /* cur:當前解決方案 n:n皇后問題 row:考慮當前解決方案的第row行 col:考慮當前解決方案的第col行 */ bool isValid(vector<string> &cur, int &n, int row, int col) { // 檢查列 for (int i = 0; i < row; i++) { if (cur[i][col] == 'Q') { return false; } } // 檢查反斜線(\) for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (cur[i][j] == 'Q') { return false; } } // 檢查斜線(/) for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { if (cur[i][j] == 'Q') { return false; } } return true; } int main() { vector<vector<string > > res = solveNQueens(4); for(int i=0; i<res.size(); i++) { for(int j=0; j<res[0].size(); j++) cout<<res[i][j]<<endl; cout<<endl; } return 0; }
執行結果
以上。