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

Added n-queen problem #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ This category should be reorganized.
- number_theory/modular_arithmetics.cc
- number_theory/primes.cc


## Backtracking

- n_queen_problem

## Other

This category should be reorganized.
Expand Down
75 changes: 75 additions & 0 deletions backtracking/n_queen_problem.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
** Provide the value of n
** This program will print one of the solution of N-Queen problem if possible for given n.
** N-Queen problem is a great example of backtracking.
** where you chose a path and if the solution is not found you backtrack to choose a different path.
*/

#include<iostream>
using namespace std;
bool grid[10001][10001];
int n;
bool isAttacked(int x, int y)
{
for(int i = 0; i < n; i++)
{
if(grid[i][y] || grid[x][i])
return true;
}
for(int i = x-1, j = y-1; i >= 0; i--, j--)
{
if(grid[i][j])
return true;
}
for(int i = x-1, j = y+1; i >= 0; i--, j++)
{
if(grid[i][j])
return true;
}
return false;
}
bool nQueen(int row)
{
if(row >= n)
return true;
for(int i = 0; i < n; i++)
{
if(!isAttacked(row, i))
{
grid[row][i] = true;
if(nQueen(row + 1))
return true;
grid[row][i] = false; //BACKTRACKING
}
}
return false;
}
int main()
{
cout<<"Enter number of queens : ";
cin>>n;
for(int i =0; i < n; i++)
for(int j = 0; j < n; j++)
grid[i][j] =false;
if(nQueen(0))
{
cout<<"Solution :-\n";
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(grid[i][j])
cout<<"Q ";
else
cout<<"- ";
}
cout<<endl;
}
}
else
{
cout<<"No Answer.\n";
}

return 0;
}