Skip to content

Commit db78625

Browse files
committed
N-queen added
1 parent 8dc9f4d commit db78625

File tree

1 file changed

+27
-47
lines changed

1 file changed

+27
-47
lines changed

51.N-Queens.cpp

Lines changed: 27 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -3,62 +3,42 @@ using namespace std;
33

44
class Solution {
55
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
6+
void solve(int col, int n, vector<string> &board,
7+
vector<vector<string>> &ans,
8+
vector<int> &leftrow, vector<int> &upperdiag, vector<int> &lowerdiag) {
9+
3610
if (col == n) {
37-
ans.push_back(temp);
11+
ans.push_back(board);
3812
return;
3913
}
4014

4115
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] = '.';
16+
if (leftrow[row] == 0 && lowerdiag[row + col] == 0 && upperdiag[(n - 1) + (col - row)] == 0) {
17+
18+
board[row][col] = 'Q';
19+
leftrow[row] = 1;
20+
lowerdiag[row + col] = 1;
21+
upperdiag[(n - 1) + (col - row)] = 1;
22+
23+
solve(col + 1, n, board, ans, leftrow, upperdiag, lowerdiag);
24+
25+
board[row][col] = '.'; // backtrack
26+
leftrow[row] = 0;
27+
lowerdiag[row + col] = 0;
28+
upperdiag[(n - 1) + (col - row)] = 0;
4929
}
5030
}
5131
}
5232

53-
// Main function to call backtracking
5433
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
34+
vector<vector<string>> ans;
35+
vector<string> board(n, string(n, '.'));
5936

60-
solve(0, temp, ans, n);
61-
return ans;
62-
}
37+
vector<int> leftrow(n, 0);
38+
vector<int> lowerdiag(2 * n - 1, 0);
39+
vector<int> upperdiag(2 * n - 1, 0);
6340

64-
};
41+
solve(0, n, board, ans, leftrow, upperdiag, lowerdiag);
42+
return ans;
43+
}
44+
};

0 commit comments

Comments
 (0)