-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add nQueens implementation printing only one possible solution
- Loading branch information
1 parent
d2ee300
commit 1611843
Showing
2 changed files
with
63 additions
and
94 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
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,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; | ||
} |