Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add N Queen problem algorithm file #77

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions c++/nqueen.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <bits/stdc++.h>
using namespace std;
int n;

bool safe(vector<vector<int>> &board, int r, int c) {
for (int i = 0; i < c; i++) if (board[r][i] == 1) return false;
for (int i = r, j = c; i >= 0 && j >= 0; i--,j--) if (board[i][j] == 1) return false;
for (int i = r, j = c; i < n && j >= 0; i++,j--) if (board[i][j] == 1) return false;
return true;
}

bool solve(vector<vector<int>> &board, int c) {
if (c >= n) return true;
else {
for (int i = 0; i < n; i++)
{
if (safe(board, i,c)) {
board[i][c] = 1;
if (solve(board, c+1)) return true;
board[i][c] = 0;
}
}
return false;
}
}

signed main()
{
cout << "Enter the value of N\n";
cin >> n;
vector<vector<int>> board(100, vector<int> (100, 0));
if (!solve(board, 0)) cout << "No Solution exists!\n";
else {
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << board[i][j] << " ";
}
cout << endl;
}

}
return 0;
}