1. Board Traversal with Upward Safety Checking
Intuition
Place Q on an N x N boolean board, checking up, up-left, and up-right in O(N) time for every placement.
When to apply: Baseline comparison with full board simulation.
Algorithm
- Initialize N x N board.
- In
solve(row): - - If
row == n,count++, return. - - For each
col: ifisSafe(row, col), place queen, recurserow + 1, backtrack.
#include <iostream>#include <vector> using namespace std; class Solution { bool isSafe(int row, int col, int n, const vector<vector<bool>>& board) { for (int i = 0; i < row; i++) if (board[i][col]) return false; for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) if (board[i][j]) return false; return true; } void solve(int row, int n, vector<vector<bool>>& board, int& count) { if (row == n) { count++; return; } for (int col = 0; col < n; col++) { if (isSafe(row, col, n, board)) { board[row][col] = true; solve(row + 1, n, board, count); board[row][col] = false; } } } public: int totalNQueens(int n) { vector<vector<bool>> board(n, vector<bool>(n, false)); int count = 0; solve(0, n, board, count); return count; }}; int main() { Solution sol; cout << sol.totalNQueens(4) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N! * N)— Explores N! states with an O(N) check per step. - Space complexity:
O(N^2)— Board array takes O(N2) memory.