user
Solve the eight queens puzzle.

You can extend the problem to solve the puzzle with a board of size   **N**x**N**.

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
assistant
(formerly Perl 6)

**Works with**: rakudo version 2015-11-29

Neither pretty nor efficient, a simple backtracking solution

```
sub MAIN(\N = 8) {
    sub collision(@field, $row) {
        for ^$row -> $i {
            my $distance = @field[$i] - @field[$row];
            return True if $distance == any(0, $row - $i, $i - $row);
        }
        False;
    }
    sub search(@field, $row) {
        return @field if $row == N;
        for ^N -> $i {
            @field[$row] = $i;
            return search(@field, $row + 1) || next
                unless collision(@field, $row);
        }
        ()
    }
    for 0 .. N / 2 {
        if search [$_], 1 -> @f {
            say @f;
            last;
        }
    }
}
```

Output:

```
[0 4 7 5 2 6 1 3]
```