标签:
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.."] ]
思路:WFS,按行递归,在每个递归过程中按列循环,此时可能会有多种选择,所以使用回溯法
class Solution { public: vector<vector<string>> solveNQueens(int n) { result.clear(); string str=""; for(int i = 0; i<n;i++) str+= "."; vector<string> answer(n,str); vector<bool> columnFlag(n,false); dfs(answer,columnFlag, n, 0); return result; } void dfs(vector<string> &answer, vector<bool> &columnFlag, int n, int depth){ //depth表示行号 if(depth == n) //递归结束条件 { result.push_back(answer); return; } bool haveAnswer = true; for(int i = 0; i < n; i++) //按列循环搜索 { if(columnFlag[i]) continue; //check column for (int j = 1; depth-j >= 0 && i-j >= 0; j++) //check upper left diagonal { if(answer[depth-j][i-j]==‘Q‘) { haveAnswer = false; break; } } if(!haveAnswer) { haveAnswer = true; continue; } for (int j = 1; depth-j >= 0 && i+j <= n-1; j++) //check upper right diagonal { if(answer[depth-j][i+j]==‘Q‘) { haveAnswer = false; break; } } if(!haveAnswer) { haveAnswer = true; continue; } //找到一种answer,递归 answer[depth][i] = ‘Q‘; columnFlag[i] = true; dfs(answer, columnFlag, n, depth+1); //回溯 answer[depth][i] = ‘.‘; columnFlag[i] = false; } } private: vector<vector<string>> result; };
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4856952.html