LeetCode OJ:N-Queens(N皇后问题)
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皇后问题,我首先是用brute force,但是这样做的话一直会TLE:
1 class Solution { 2 public: 3 vector<vector<string>> solveNQueens(int n) { 4 vector<int> board(n); 5 vector<vector<string>> ret; 6 vector<string> tmpVec; 7 for(int i = 0; i < n; ++i){ 8 board[i] = i + 1;//确保了上下左右不会有相邻的元素 9 } 10 vector<int> afterAdd(n); 11 vector<int> afterSub(n); 12 for(;;){ 13 transform(board.begin(), board.end(), afterAdd.begin(),
[](int i)->int{static int index = 1; i += index; index++; return i;}); 14 transform(board.begin(), board.end(), afterSub.begin(),
[](int i)->int{static int index = 1; i -= index; index++; return i;}); 15 set<int>afterSubSet(afterSub.begin(), afterSub.end()); 16 set<int>afterAddSet(afterAdd.begin(), afterAdd.end()); 17 if(afterAddSet.size() == n && afterSubSet.size() == n){ 18 for(int i = 0; i < n; i++){ 19 string tmp = ""; 20 for(int j = 0; j < n; ++j){ 21 tmp.append(1, j == board[i]-1 ? 'Q' : '.'); 22 } 23 tmpVec.push_back(tmp); 24 tmp.clear(); 25 } 26 ret.push_back(tmpVec); 27 tmpVec.clear(); 28 } 29 if(!next_permutation(board.begin(), board.end())){ 30 return ret; 31 break; 32 } 33 } 34 } 35 };
后来就只能使用dfs了,代码如下:
1 class Solution { 2 public: 3 vector<vector<string>> solveNQueens(int n) { 4 ret.clear(); 5 memset(canUse, true, sizeof(canUse)); 6 dfs(0,n); 7 return ret; 8 } 9 10 bool check(int pos, int line) 11 { 12 for(int i = 0; i < line; ++i){ 13 if(line - i == abs(pos - a[i])) //这一步很重要 14 return false; //相差n行的两个皇后的位置不可以也正好相差n个,那样一定是不可以的15 } 16 return true; 17 } 18 19 void dfs(int dep, int maxDep) 20 { 21 if(dep == maxDep){ 22 vector<string> tmpVec; 23 for(int i = 0; i < maxDep; ++i){ 24 string tmp = ""; 25 for(int j = 0; j < maxDep; ++j){ 26 tmp.append(1, j == a[i] ? 'Q' : '.'); 27 } 28 tmpVec.push_back(tmp); 29 tmp.clear(); 30 } 31 ret.push_back(tmpVec); 32 tmpVec.clear(); 33 } 34 for(int i = 0; i < maxDep; ++i){ 35 if(canUse[i] && check(i, dep)){ 36 canUse[i] = false; 37 a[dep] = i; 38 dfs(dep + 1, maxDep); 39 canUse[i] = true; 40 } 41 } 42 } 43 private: 44 vector<vector<string>> ret; 45 int a[100]; 46 bool canUse[100]; 47 };