Skip to content

Commit

Permalink
Add nQueens implementation printing only one possible solution
Browse files Browse the repository at this point in the history
  • Loading branch information
nandwalritik committed Apr 24, 2021
1 parent d2ee300 commit 1611843
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 94 deletions.
94 changes: 0 additions & 94 deletions rbtr/nQueens.c

This file was deleted.

63 changes: 63 additions & 0 deletions rbtr/nQueens.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#include<bits/stdc++.h>
using namespace std;
bool isSafe(int** arr,int x,int y,int n){
for(int row=0;row<x;row++){
if(arr[row][y] == 1){
return false;
}
}
int row=x,col=y;
while(row >= 0 && col >= 0){
if(arr[row][col] == 1){
return false;
}
row--;
col--;
}
row=x,col=y;
while(row >= 0 && col < n){
if(arr[row][col] == 1){
return false;
}
row--;
col++ ;
}
return true;
}
bool nQueens(int **arr,int x,int n){
if(x >= n){
return true;
}
bool ans=false;
for(int col=0;col<n;col++){
if(isSafe(arr,x,col,n)){
arr[x][col] = 1;
if(nQueens(arr,x+1,n)){
return true;
}
arr[x][col] = 0;
}
}
return false;
}
int main(){
int n = 5;
int** arr = new int*[n];
for(int i=0;i<n;i++){
arr[i] = new int[n];
for(int j=0;j<n;j++){
arr[i][j]=0;
}
}

if(nQueens(arr,0,n)){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}

return 0;
}

0 comments on commit 1611843

Please sign in to comment.