比较 n 女王的 next_permutation 函数

compare function in next_permutation for n-queen

本文关键字:permutation 函数 next 女王 比较      更新时间:2023-10-16

我正在尝试使用 c++ STL 中的内置 next_permutation 函数解决 n-queen 问题。 与 n Queen 一样,一个有效的排列是前一个 Queen 不应该与当前相邻的排列,即 abs(current_queen_index - prev_queen_index( != 1 我试图为相同的函数创建一个比较函数,但它没有返回任何内容。

bool isValid(int cur_pos, int prev_pos) {
return ( abs(cur_pos - prev_pos) != 1 );
}
int main() {
vector<int> v = { 0, 1, 2, 3 };
do {
cout<<v[0]<<" "<<v[1]<<" "<<v[2]<<" "<<v[3]<<"n";
} while( next_permutation(v.begin(), v.end(), isValid));
}

最后一个参数是一个比较函数,而不是一个isValid

如果使用std::next_permutation,则可以检查完整的排列。

bool isNotValid(int cur_pos, int prev_pos) {
return std::abs(cur_pos - prev_pos) == 1;
}
int main() {
std::vector<int> v = { 0, 1, 2, 3 };
do {
if (std::adjacent_find(v.begin(), v.end(), &isNotValid) == v.end()) {
std::cout<<v[0]<<" "<<v[1]<<" "<<v[2]<<" "<<v[3]<<"n";
}
} while (std::next_permutation(v.begin(), v.end()));
}

演示

请注意,对有效排列的检查适用于大小 4,但通常是错误的。