标签:
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.."] ]
[solution]
1 vector<vector<string> > result; 2 vector<vector<string> > solveNQueens(int n) 3 { 4 if (n <= 0) 5 return result; 6 vector<int> mark(n, 0); 7 8 NQueen(mark, n, 0); 9 return result; 10 } 11 12 void NQueen(vector<int> &mark, int n, int row) 13 { 14 if (row == n) // get a solution 15 { 16 vector<string> strRow; 17 for (int i = 0; i < n; i++) 18 { 19 string str; 20 for (int j = 0; j < n; j++) 21 if (mark[i] == j) 22 str.push_back(‘Q‘); 23 else 24 str.push_back(‘.‘); 25 strRow.push_back(str); 26 } 27 result.push_back(strRow); 28 return; 29 } 30 31 for (int i = 0; i < n; i++) 32 { 33 mark[row] = i; 34 if (check(mark, row)) 35 NQueen(mark, n, row + 1); 36 } 37 } 38 39 bool check(vector<int> mark, int row) 40 { 41 for (int i = 0; i < row; i++) 42 { 43 if (mark[i] == mark[row] || abs(mark[i] - mark[row]) == (row - i)) 44 return false; 45 } 46 return true; 47 }
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4321663.html