N-Queens (Count the Solutions)

Problem

Place n queens on an n x n chess board so that no two queens attack each other (no two on the same row, column or diagonal). Read n and print the number of different solutions.

Constraints

  • 1 <= n <= 9

Examples

Input

4

Output

2

Solutions

Best approachTime O(n!)Space O(n)

We place one queen in each row. For every row we try each column that is not attacked. Three arrays mark the used columns and diagonals, so each test costs O(1). If we reach the last row, we found a solution.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count the N-Queens solutions.
 * Input   : One integer n.
 * Output  : The number of solutions.
 * Approach: One queen per row.
 * Time    : O(n!)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        // This method counts the ways to place queens in the rows row, row + 1, ..., n - 1.
        // The three arrays remember which columns and diagonals are already attacked.
        static int place(int row, int n, boolean[] columns, boolean[] diagonal1, boolean[] diagonal2) {
            // Step 1: All rows are filled. This is one valid solution.
            if (row == n) {
                return 1;
            }

            int count = 0;
            for (int column = 0; column < n; column++) {
                // Step 2: Cells on the same column or diagonal have the same index values. Skip attacked cells.
                if (columns[column] || diagonal1[row - column + n - 1] || diagonal2[row + column]) {
                    continue;
                }

                // Step 3: Place the queen, count the solutions for the next rows, then remove the queen.
                columns[column] = true;
                diagonal1[row - column + n - 1] = true;
                diagonal2[row + column] = true;
                count += place(row + 1, n, columns, diagonal1, diagonal2);
                columns[column] = false;
                diagonal1[row - column + n - 1] = false;
                diagonal2[row + column] = false;
            }
            return count;
        }

    // This method solves the task. It receives the input and returns the answer.
    static int solve(long n) {
        int size = (int) n;
        return place(0, size, new boolean[size], new boolean[2 * size], new boolean[2 * size]);
    }

    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        System.out.println(solve(n));
    }
}
Hints (2)
  1. Why is one queen per row enough?
  2. Which formula identifies a diagonal?