forked from avastino7/Algorithms-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queens.cpp
51 lines (46 loc) · 2.28 KB
/
N-Queens.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
*/
class Solution {
public:
vector<vector<string> > sols; // 2D vector of strings to store the solutions
vector<vector<string>> solveNQueens(int n) {
vector<string> board(n, string(n, '.')); // creating an empty board
solve(board, 0); // calling the recursive function
return sols;
}
bool isSafe(vector<string>& board, int row, int col) {
int n = size(board);
for(int i = 0; i < n; i++) {
// checking if there is a queen in the same column
if(board[i][col] == 'Q') return false;
// checking if there is a queen in the same diagonal (left to right)
if(row - i >= 0 && col - i >= 0 && board[row - i][col - i] == 'Q') return false;
if(row - i >= 0 && col + i < n && board[row - i][col + i] == 'Q') return false;
// No need to traverse more since the lower rows below current row attribute will always be safe.
/* if(row + i < n && col - i >= 0 && board[row + i][col - i] == 'Q') return false;
if(row + i < n && col + i < n && board[row + i][col + i] == 'Q') return false; */
}
return true;
}
// Recursive Function (solve) - It basically tries all possible placement of queen for the current row & recurses for it's next row
void solve(vector<string>& board, int row) {
// Base condition.
// We reached the last row, so we have a solution so we add it to the solution vector
if(row == size(board)) {
sols.push_back(board);
return;
}
// Try placing a queen on each column for a given row.
// Explore next row by placing Q at each valid column for the current row
for(int col = 0; col < size(board); col++){
if(isSafe(board, row, col)) {
board[row][col] = 'Q'; // Queen placed on a valid cell
solve(board, row + 1); // Exploring next row
board[row][col] = '.'; // Backtracking to get all possible solutions
}
}
}
};