N-Queens in Java: Explanation & Practice

Place N queens on NxN board with no attacks

Problem summary

Place N queens on an N×N chessboard such that no two queens attack each other. Return all distinct solutions.

Starter code

public class Main {
    public static void main(String[] args) {
        int n = 4;
        
        // Place queens row by row
        // For each row, try each column
        // Check if position is safe (no queen in same col, diagonals)
        // Print number of solutions
    }
}

Expected output and test cases

  • 4-Queens has 2 solutions
    Solutions: 2
  • 1-Queen has 1 solution
    Solutions: 1
  • 2-Queens and 3-Queens have 0 solutions
    Solutions: 0

Hints

  1. Place one queen per row (try each column)
  2. Use sets/arrays to track: columns used, diagonals used
  3. For diagonals: row-col is constant for one diagonal, row+col for other
  4. Backtrack when no valid column found

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler