Skip to content

Commit

Permalink
Merge pull request #286 from RohitVishwakarma8840/patch-1
Browse files Browse the repository at this point in the history
N*N Queen Bactracking
  • Loading branch information
AkhzarFarhan authored Oct 30, 2024
2 parents 6c95d47 + 9397d1b commit 8e733a0
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions C++/Backtracking/N*N Queen Bactracking
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include <bits/stdc++.h>
using namespace std;

void printSolution(vector<vector<int>>& board, int N) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
cout << (board[i][j] ? "Q " : ". ");
}
cout << endl;
}
cout << endl;
}

bool isSafe(vector<vector<int>>& board, int row, int col, int N) {
for (int i = 0; i < col; ++i)
if (board[row][i]) return false;

for (int i = row, j = col; i >= 0 && j >= 0; --i, --j)
if (board[i][j]) return false;

for (int i = row, j = col; i < N && j >= 0; ++i, --j)
if (board[i][j]) return false;

return true;
}

bool solveNQueensUtil(vector<vector<int>>& board, int col, int N) {
if (col >= N) {
printSolution(board, N);
return true;
}

bool res = false;
for (int i = 0; i < N; ++i) {
if (isSafe(board, i, col, N)) {
board[i][col] = 1;
res = solveNQueensUtil(board, col + 1, N) || res;
board[i][col] = 0;
}
}
return res;
}

void solveNQueens(int N) {
vector<vector<int>> board(N, vector<int>(N, 0));
if (!solveNQueensUtil(board, 0, N)) {
cout << "No solution exists\n";
}
}

int main() {
int N;
cout << "Enter the number of queens: ";
cin >> N;
solveNQueens(N);
return 0;
}

0 comments on commit 8e733a0

Please sign in to comment.