DevPath

← All problems

N-Queens Count

Hard backtracking

Description

Return the number of ways to place n queens on an n by n board so that none attack each other.

Constraints

1 <= n <= 9

Examples

Input: n = 4

Output: 2

Hints (1)
  • Place one queen per row, tracking used columns and both diagonals.

Solutions

Row-by-row backtracking with sets. · Time exponential · Space O(n)

func totalNQueens(n int) int {
    cols, diag1, diag2 := map[int]bool{}, map[int]bool{}, map[int]bool{}
    count := 0
    var place func(row int)
    place = func(row int) {
        if row == n {
            count++
            return
        }
        for col := 0; col < n; col++ {
            if cols[col] || diag1[row-col] || diag2[row+col] {
                continue
            }
            cols[col] = true
            diag1[row-col] = true
            diag2[row+col] = true
            place(row + 1)
            delete(cols, col)
            delete(diag1, row-col)
            delete(diag2, row+col)
        }
    }
    place(0)
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account