【发布时间】: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