-
Notifications
You must be signed in to change notification settings - Fork 238
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #286 from RohitVishwakarma8840/patch-1
N*N Queen Bactracking
- Loading branch information
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |