1. Board Traversal with O(N) Safety Check Function
Intuition
For each row, iterate col from 0 to n - 1. Check safety with helper function isSafe(row, col) that scans vertically up, diagonally up-left, and diagonally up-right. If safe, place Q and recurse.
When to apply: Intuitive baseline without auxiliary lookup arrays.
Algorithm
- In
isSafe(row, col): - - Check column: iterate
ifrom 0 torow - 1, ifboard[i][col] == 'Q', return false. - - Check up-left:
i = row-1, j = col-1while>= 0, ifboard[i][j] == 'Q', return false. - - Check up-right:
i = row-1, j = col+1whilei >= 0, j < n, ifboard[i][j] == 'Q', return false. - - Return true.
- In
solve(row): iterate cols, checkisSafe, recurserow + 1, backtrack.
#include <iostream>#include <vector>#include <string> using namespace std; class Solution { bool isSafe(int row, int col, int n, const vector<string>& board) { // Check column upward for (int i = 0; i < row; i++) { if (board[i][col] == 'Q') return false; } // Check top-left diagonal for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == 'Q') return false; } // Check top-right diagonal for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { if (board[i][j] == 'Q') return false; } return true; } void solve(int row, int n, vector<string>& board, vector<vector<string>>& result) { if (row == n) { result.push_back(board); return; } for (int col = 0; col < n; col++) { if (isSafe(row, col, n, board)) { board[row][col] = 'Q'; solve(row + 1, n, board, result); board[row][col] = '.'; // backtrack } } } public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> result; vector<string> board(n, string(n, '.')); solve(0, n, board, result); return result; }}; int main() { Solution sol; auto res = sol.solveNQueens(4); for (const auto& b : res) { for (const string& row : b) cout << row << endl; cout << "---" << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(N! * N)— There are N! placements explored, each performing an O(N) safety check. - Space complexity:
O(N^2)— Board of size N x N.