【问题标题】:More efficient algorithm to count attacks in N-queens?更有效的算法来计算 N 皇后中的攻击?
【发布时间】:2016-02-16 12:38:30
【问题描述】:

我正在研究基于 DFS 的 N 皇后问题解决方案。

我将棋盘状态存储为一个 int[N] 数组,表示每列中皇后的垂直位置(例如,皇后在 6x6 棋盘对角线下方的位置将是 state = { 0, 1, 2, 3, 4 , 5 }),其中 -1 表示“此列中没有皇后”。

我当前在给定状态配置中计算女王攻击的算法的复杂度为 O(n^2):

function count_attacks(state)

    attack_count = 0

    for each column index c1
      if state[c1] == -1 continue

      for each column index c2 further along than c1
        if state[c2] == -1 continue

        // Lined up horizontally?
        if state[c1] == state[c2] attack_count++    

        // Lined up diagonally?
        else if (c2 - c1) == abs(state[c2] - state[c1]) attack_count++   

       // No need to check lined up vertically as impossible with this state representation

    return attack_count;

当求解 N=500+ 时,O(N^2) 会降低性能。

是否有可能比 O(N^2) 更好地计算攻击次数?

【问题讨论】:

    标签: algorithm big-o asymptotic-complexity n-queens


    【解决方案1】:

    定义数组

    rows, columns, left_diagonals, right_diagonals
    

    分别计算i-th 行、列、左对角线(所有xy 使得x-y=c 对于一些c)、右对角线(所有@987654328 @ 和 y 使得 x+y=c 对于某些 c)。那么算法将是:

    Intialize rows, columns, left_diagonals, right_diagonals with zero values
    attacks = 0
    for queen in queens
        attacks += rows[queen.row];
        attacks += columns[queen.column];
        attacks += left_diagonals[queen.left_diagonal];
        attacks += right_diagonals[queen.right_diagonal];
        rows[queen.row]++;
        columns[queen.column]++;
        left_diagonals[queen.left_diagonal]++;
        right_diagonals[queen.right_diagonal]++;
    

    但是,为了解决Nqueen 问题,您不需要检查攻击次数。您只需要检查是否存在攻击。

    此外,如果您正在寻找问题的单一解决方案,可以使用 very efficient algorithm

    【讨论】:

    • 很好地观察到不需要计算攻击次数
    • 是的,很好的观察,这可能是 DFS 的巨大改进。不过需要注意的是,如果您打算使用启发式算法,那么您可能需要完整的攻击计数。
    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多