

Solve the eight queens puzzle.



You can extend the problem to solve the puzzle with a board of size   NxN.

For the number of solutions for small values of   N,   see   OEIS: A000170.



Related tasks

 A* search algorithm
 Solve a Hidato puzzle
 Solve a Holy Knight's tour
 Knight's tour
 Peaceful chess queen armies
 Solve a Hopido puzzle
 Solve a Numbrix puzzle
 Solve the no connection puzzle


func N_queens_solution(N = 8) {
 
    func collision(field, row) {
        for i in (^row) {
            var distance = (field[i] - field[row])
            distance ~~ [0, row-i, i-row] && return true
        }
        return false
    }
 
    func search(field, row) {
        row == N && return field
        for i in (^N) {
            field[row] = i
            if (!collision(field, row)) {
                return (__FUNC__(field, row+1) || next)
            }
        }
        return []
    }
 
    for i in (0 .. N>>1) {
        if (var r = search([i], 1)) {
            return r
        }
    }
}
 
for n in (1..15) {
    say "#{'%2d' % n}: #{N_queens_solution(n) || 'No solution'}"
}