首页 > 代码库 > N皇后问题

N皇后问题

代码:

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皇后问题