l*****c 发帖数: 316 | 1 N皇后,写出来总是报错
说我placeQueen里面没有声明vector>& reta
好久没写C++了。请帮忙提个错
多谢
vector > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector> ret = new vector>();
if (n <= 0) {
return ret;
}
int * sol = new int[n];
placeQueen(sol, n, 0, ret);
return ret;
}
void placeQueen(int sol[], int n, int row, vector>& reta)
{
if (row == n) {
reta.push_back(transform(sol),n);
return;
}
for (int i = 0; i < n; i++) {
if (!taken(sol, row, i)) {
sol[row] = i;
placeQueen(sol, n, row+1, reta);
}
}
} | b*********h 发帖数: 103 | | q********c 发帖数: 1774 | 3 A couple problems:
1. when you use new, you should return a pointer
2. You don't need new for vector, so use this:
vector > ret; | l*****c 发帖数: 316 | 4 thanks ! Now it's ok.
vector > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//vector> ret = new vector>();
vector > ret;
if (n <= 0) {
return ret;
}
int * sol = new int[n];
placeQueen(sol, n, 0, ret);
return ret;
}
void placeQueen(int sol[], int n, int row, vector >& reta
) {
if (row == n) {
reta.push_back(transform(sol, n));
return;
}
for (int i = 0; i < n; i++) {
if (!taken(sol, row, i)) {
sol[row] = i;
placeQueen(sol, n, row+1, reta);
}
}
}
bool taken(int sol[], int row, int col) {
//check col and diag
for (int i = 0; i < row; i++) {
if (sol[i] == col) {
return true;
}
if (row-i == abs(col-sol[i])) {
return true;
}
}
return false;
}
vector transform(int sol[], int n){
vector ret;
for (int i = 0; i < n; i++) {
string sb ="";
for (int j = 0; j < n; j++) {
if (j == sol[i]) {
sb=sb+"Q";
}
else {
sb=sb+".";
}
}
ret.push_back(sb);
}
return ret;
}
【在 q********c 的大作中提到】 : A couple problems: : 1. when you use new, you should return a pointer : 2. You don't need new for vector, so use this: : vector > ret;
|
|