Author: Spiros Nikoloudakis (@grsprs)
A backtracking algorithm implementation in Go that solves the N-Queens problem.
Place N queens on an N×N chessboard such that no two queens attack each other. Queens attack along rows, columns, and diagonals.
This implementation uses backtracking with constraint propagation:
- Places one queen per row
- Tracks occupied columns and diagonals using hash maps
- Prunes invalid branches early
- Finds all distinct valid arrangements
go run queens.goInput N when prompted. The program outputs all solutions and the total count.
Input:
4
Output:
Solution 1:
.Q..
...Q
Q...
..Q.
Solution 2:
..Q.
Q...
...Q
.Q..
Total solutions: 2
go buildgo test -vAll tests validate correctness against known solution counts and verify no queens attack each other.
- N=8: 92 solutions in <100ms
- N=12: completes within seconds
- Constraint: 1 ≤ N ≤ 12
queens.go: Main solver with backtracking algorithmqueens_test.go: Comprehensive test suite
https://github.com/grsprs/queens
MIT License - see LICENSE file