更有效的算法来计算N皇后的攻击?

时间:2016-02-16 12:38:31

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

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

我将电路板状态存储为int [N]数组,表示每列中皇后的垂直位置(例如,沿6x6电路板对角放置的皇后将是状态= {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)更好地计算攻击?

1 个答案:

答案 0 :(得分:3)

定义数组

rows, columns, left_diagonals, right_diagonals

分别计算i - 行,列,左对角线(所有xy中的王后数量,以便某些x-y=c c }}),右对角线(所有xyx+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]++;

但是,要解决N女王问题,您不需要检查攻击次数。您只需要检查是否存在攻击。

此外,如果您正在寻找问题的单一解决方案,则有very efficient algorithm