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:

In first method, pos[i] represents the column location of the i row.

In the second method, a flag array is used to record the location on the column, 45 degree diagonal, 135 degree diagonal. It can be separated into three flag arrays. 1. flag_col with the size of n 2. flag_45 with the size of 2 * n - 1 3. flag_135 with the size of 2 * n - 1 We need to check them when reaching location (row, col) by flag_col[col], flag_45[row + col], and flag_135[n - 1 + col - row]. Finally, three flag arrays can be combined into one, which has the size of 5 * n - 2. For column checking => flag[col]

for 45-degree diagonal checking => flag[n + row + col]

for 135-degree diagonal checking => flag[n + 2 * n - 1 + n - 1 + col - row]

The following explanation comment is copied from https://leetcode.com/problems/n-queens/discuss/19808/Accepted-4ms-c++-solution-use-backtracking-and-bitmask-easy-understand.

Last updated

Was this helpful?