【问题标题】:compare function in next_permutation for n-queen比较 n-queen 的 next_permutation 函数
【发布时间】:2020-05-22 17:06:50
【问题描述】:

我正在尝试使用 c++ STL 中内置的 next_permutation 函数来解决 n-queen 问题。 与 n 皇后一样,有效的排列是前一个皇后不应与当前皇后相邻的排列,即 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));

}

【问题讨论】:

  • “但它没有返回任何东西”你的意思是什么?..

标签: c++ stl permutation n-queens


【解决方案1】:

最后一个参数是比较函数,而不是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()));
}

Demo

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

【讨论】:

  • 太好了,我得到了你的解决方案,但是有什么方法可以单独使用 next_permutaion 或任何其他更好或更有效的方法,我不需要生成完整的排列列表跨度>
  • 我不会使用置换,而是使用回溯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 2020-09-10
相关资源
最近更新 更多