码迷,mamicode.com
首页 > 其他好文 > 详细

N皇后问题

时间:2017-08-07 01:23:45      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:position   []   代码   log   let   com   boa   oar   abs   

代码:

class Solution {
public:
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string ‘...Q‘ shows a queen on forth position
*/
vector<vector<string> > solveNQueens(int n) {
// write your code here
if(n == 1) {
vector<vector<string> > result;
vector<string> strOneRow;
strOneRow.push_back("Q");
result.push_back(strOneRow);
return result;
}
else if(n < 4) {
return vector<vector<string> > ();
}

vector<vector<string> > result;
int i;

int *pCheckerboard = new int[n];
for(i=0; i<n; i++) {
pCheckerboard[i] = -1;
}

queensRecursively(0, n, pCheckerboard, result);

delete[] pCheckerboard;
return result;
}

void queensRecursively(int row, int n, int *pCheckerboard, vector<vector<string> > &result) {
int i = 0, j = 0;
if(n == row) {
vector<string> strOneRow;
for(i=0; i<n; i++) {
string str;
for(j=0; j<n; j++) {
str += ‘.‘;
}
if(pCheckerboard[i]>=0 && pCheckerboard[i]<n) {
str[pCheckerboard[i]] = ‘Q‘;
}
strOneRow.push_back(str);

}
result.push_back(strOneRow);
}
else {
for(i=0; i<n; i++) {
if(canPlace(row, i, n, pCheckerboard)) {
pCheckerboard[row] = i;
queensRecursively(row+1, n, pCheckerboard, result);
}
}
}
}

int canPlace(int row, int col, int n, int *pCheckerboard) {
int i;
for(i=0; i<n && i!=row; i++) {
if(pCheckerboard[i] == col) {
return 0;
}
if(abs(row-i) == abs(col-pCheckerboard[i])) {
return 0;
}
}
return 1;
}
};

截图:

技术分享

N皇后问题

标签:position   []   代码   log   let   com   boa   oar   abs   

原文地址:http://www.cnblogs.com/w1500802028/p/7296520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!