মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 7 · Backtracking

7.2 N-Queens & Board Puzzles

চিনবেন কীভাবে
placements on a board, "no two attack each other", sudoku — track occupied lines with a Set/array so the constraint check is fast
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: N-QueensLC 51 (Hard — Meta/Google High)

Statement (Demo): Place n queens on an n × n chessboard so that no two attack each other. Return every distinct solution. Example: n=4[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] | ⚡ 1 ≤ n ≤ 9

Approach: Place one queen per row. Keep the occupied column and both diagonals in three Sets — the trick for diagonals is that row - col and row + col stay constant along them.

function solveNQueens(n) {
  const res = [];
  const board = Array.from({ length: n }, () => new Array(n).fill("."));
  const cols = new Set(),
    diag1 = new Set(),
    diag2 = new Set();
  const place = (row) => {
    if (row === n) {
      res.push(board.map((r) => r.join("")));
      return;
    }
    for (let col = 0; col < n; col++) {
      if (cols.has(col) || diag1.has(row - col) || diag2.has(row + col))
        continue;
      cols.add(col);
      diag1.add(row - col);
      diag2.add(row + col);
      board[row][col] = "Q";
      place(row + 1);
      board[row][col] = "."; // undo
      cols.delete(col);
      diag1.delete(row - col);
      diag2.delete(row + col);
    }
  };
  place(0);
  return res;
}

Complexity: Time O(n!), Space O(n²)

নোট · ফাঁকা

প্রবলেম

  • Sudoku SolverLC 37
    (Hard — try 1–9 in each empty cell, undo when invalid)

    Statement: Solve a 9 × 9 Sudoku board in place. Empty cells are marked ..
    Example: classic Sudoku rules | ⚡ the puzzle has exactly one solution

    নোট · ফাঁকা