Skip to content

Commit 45450f0

Browse files
authored
Merge pull request #138 from sujanrupu/main
Added N-Queens Problem Solution
2 parents 535e60a + aaae15a commit 45450f0

1 file changed

Lines changed: 84 additions & 0 deletions

File tree

CPP/Backtracking/N_queens.cpp

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
Problem statement :
3+
4+
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.
5+
6+
Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
7+
8+
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
9+
Input: n = 4
10+
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
11+
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
12+
Example 2:
13+
14+
Input: n = 1
15+
Output: [["Q"]]
16+
17+
18+
Constraints:
19+
20+
1 <= n <= 9
21+
*/
22+
23+
#include <bits/stdc++.h>
24+
using namespace std;
25+
26+
class Solution {
27+
public:
28+
// check if placing queen at (row,col) is safe
29+
bool isSafe(vector<vector<int>>& board, int row, int col) {
30+
int x = row, y = col;
31+
while (y >= 0) if (board[x][y--] == 1) return false;
32+
x = row; y = col;
33+
while (x < board.size() && y >= 0) if (board[x++][y--] == 1) return false;
34+
x = row; y = col;
35+
while (x >= 0 && y >= 0) if (board[x--][y--] == 1) return false;
36+
return true;
37+
}
38+
39+
// convert board to string format
40+
void addSol(vector<vector<int>>& board, int n, vector<vector<string>>& ans) {
41+
vector<string> arr;
42+
for (int i = 0; i < n; i++) {
43+
string str = "";
44+
for (int j = 0; j < n; j++)
45+
str.push_back(board[i][j] ? 'Q' : '.');
46+
arr.push_back(str);
47+
}
48+
ans.push_back(arr);
49+
}
50+
51+
// backtrack to find all solutions
52+
void solve(vector<vector<int>>& board, int n, int col, vector<vector<string>>& ans) {
53+
if (col == n) { addSol(board, n, ans); return; }
54+
for (int row = 0; row < n; row++) {
55+
if (isSafe(board, row, col)) {
56+
board[row][col] = 1;
57+
solve(board, n, col + 1, ans);
58+
board[row][col] = 0;
59+
}
60+
}
61+
}
62+
63+
vector<vector<string>> solveNQueens(int n) {
64+
vector<vector<int>> board(n, vector<int>(n, 0));
65+
vector<vector<string>> ans;
66+
solve(board, n, 0, ans);
67+
return ans;
68+
}
69+
};
70+
71+
int main() {
72+
int n;
73+
cout << "Enter number of queens: ";
74+
cin >> n;
75+
Solution s;
76+
auto res = s.solveNQueens(n);
77+
cout << "Total Solutions: " << res.size() << "\n\n";
78+
for (auto& sol : res) {
79+
for (auto& row : sol)
80+
cout << row << "\n";
81+
cout << "\n";
82+
}
83+
return 0;
84+
}

0 commit comments

Comments
 (0)