I'm working on a DFS based solution to the N-queens problem.
I store the board state as an int[N] array representing the vertical placements of queens in each column (eg. placement of the queens diagonally down a 6x6 board would be state = { 0, 1, 2, 3, 4, 5 }), where -1 represents "no queen in this column".
My current algorithm for counting the queen attacks in a given state configuration has complexity of 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;
The O(N^2) kills performance when solving for say N=500+.
Is it possible to do better than O(N^2) for counting attacks?