52. N-Queens II

The n-queens puzzle is the problem of placing n queens on an n× n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

Thoughts:

  1. Backtracking:

    1. Having 3 boolean vectors, col, diag, anti-diag to mark where there is a queen on the same column, same diagnal, or same anti-diagnal. for col, the level set is col; for diagnal: the level set is col - row + n; for antidiagnal: the level set is row + col.

    2. for each row, expanding the cols and check where there is a queen in col, diag, and anti-diag, then recursively call the backtracking until the row reaches the end or did get in depth due to the disqualification of the results.

Code:

Last updated

Was this helpful?