写了一个Queens的backtrack 大牛帮我看看# JobHunting - 待字闺中
C*U
1 楼
如果用的是vector而不是数组的话 无法通过online judge large
哪里可以再优化一下啊?
谢谢了
int placeQueens(int n) {
int count = 0;
int *positions = new int[n];
int p = 0;
positions[p] = 0;
int i = 0;
while(!(p == -1 && i == n)) {
bool flag = true;
while(flag && i < n) {
int j = 0;
while(j < p + 1) {
if(positions[j] == i || positions[j] - i == j - (p + 1)||
positions[j] - i == p + 1 - j) {
break;
}
else {
j++;
}
}
if(j == p + 1) {
flag = false;
}
else {
i++;
}
}
if(i == n) {
if(p > -1 && positions[p] == n - 1) {
p--;
}
else if(p == -1) {
break;
}
else {
i = positions[p--] + 1; }
}
else {
positions[++p] = i;
i = 0 ;
}
if(p + 1 == n) {
count++;
i = positions[p] + 1;
p--;
}
}
return count;
}
哪里可以再优化一下啊?
谢谢了
int placeQueens(int n) {
int count = 0;
int *positions = new int[n];
int p = 0;
positions[p] = 0;
int i = 0;
while(!(p == -1 && i == n)) {
bool flag = true;
while(flag && i < n) {
int j = 0;
while(j < p + 1) {
if(positions[j] == i || positions[j] - i == j - (p + 1)||
positions[j] - i == p + 1 - j) {
break;
}
else {
j++;
}
}
if(j == p + 1) {
flag = false;
}
else {
i++;
}
}
if(i == n) {
if(p > -1 && positions[p] == n - 1) {
p--;
}
else if(p == -1) {
break;
}
else {
i = positions[p--] + 1; }
}
else {
positions[++p] = i;
i = 0 ;
}
if(p + 1 == n) {
count++;
i = positions[p] + 1;
p--;
}
}
return count;
}