1+ #include < bits/stdc++.h>
2+ using namespace std ;
3+
4+ class Solution {
5+ public:
6+ // Function to check if placing a queen at (row, col) is safe
7+ bool isSafe (int row, int col, vector<string> &temp, int n) {
8+ int duprow = row;
9+ int dupcol = col;
10+ // Check all columns to the left in the same row
11+ for (int j = 0 ; j < col; j++) {
12+ if (temp[row][j] == ' Q' ) return false ;
13+ }
14+
15+ // Check upper-left diagonal
16+ while (row >= 0 && col >= 0 ){
17+ if (temp[row][col] == ' Q' ) return false ;
18+ row--;
19+ col--;
20+ }
21+ row = duprow;
22+ col = dupcol;
23+ // Check lower-left diagonal
24+ while (row < n && col >= 0 ){
25+ if (temp[row][col] == ' Q' ) return false ;
26+ row++;
27+ col--;
28+ }
29+
30+ return true ;
31+ }
32+
33+ // Backtracking function to place queens column by column
34+ void solve (int col, vector<string> temp, vector<vector<string>> &ans, int n) {
35+ // If all columns are filled, add current board to answer
36+ if (col == n) {
37+ ans.push_back (temp);
38+ return ;
39+ }
40+
41+ for (int row = 0 ; row < n; row++) {
42+ if (isSafe (row, col, temp, n)) {
43+ // Place queen
44+ temp[row][col] = ' Q' ;
45+ // Recurse for next column
46+ solve (col + 1 , temp, ans, n);
47+ // Backtrack and remove queen
48+ temp[row][col] = ' .' ;
49+ }
50+ }
51+ }
52+
53+ // Main function to call backtracking
54+ vector<vector<string>> solveNQueens (int n) {
55+ vector<vector<string>> ans;
56+ vector<string> temp;
57+ string s (n, ' .' );
58+ for (int i = 0 ; i < n ; i++) temp.push_back (s); // FIXED
59+
60+ solve (0 , temp, ans, n);
61+ return ans;
62+ }
63+
64+ };
0 commit comments