LeetcodeAug 11, 2025

N-Queens II

Hazrat Ali

Leetcode

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

 

Example 1:

Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.

Example 2:

Input: n = 1
Output: 1

Solution
/**
 * @param {number} n
 * @return {number}
 */
const totalNQueens = n => {
  const isValid = (row, columns) => {
    for (let i = 0; i < row; i++) {
      if (columns[i] === columns[row]) {
        return false;
      }

      if (row - i === Math.abs(columns[row] - columns[i])) {
        return false;
      }
    }

    return true;
  };

  const backtracking = (n, row, columns) => {
    if (row === n) {
      count++;
      return;
    }

    for (let j = 0; j < n; j++) {
      columns[row] = j;

      if (isValid(row, columns)) {
        backtracking(n, row + 1, columns);
      }
    }
  };

  let count = 0;
  backtracking(n, 0, []);
  return count;
};



Comments