Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- bool valid(vector<vector<int>>&ans,vector<vector<int>>&v,int row,int col,int n){
- for(int i=0;i<row;i++){
- if(v[i][col]==1)return false;
- }
- for(int i=row-1,j=col-1;i>=0 && j>=0;i--,j--){
- if(v[i][j]==1)return false;
- }
- for(int i=row-1,j=col+1;i>=0 && j<n;i--,j++){
- if(v[i][j]==1)return false;
- }
- return true;
- }
- void solve(vector<vector<int>>&ans,vector<vector<int>>&v,int row,int n){
- if(row==n){
- vector<int>idx;
- for(int i=0;i<n;i++){
- for(int j=0;j<n;j++){
- if(v[i][j]==1)idx.push_back(j+1);
- }
- }
- ans.push_back(idx);
- }
- else{
- for(int col=0;col<n;col++){
- if(valid(ans,v,row,col,n)==true){
- v[row][col]=1;
- solve(ans,v,row+1,n);
- v[row][col]=0;
- }
- }
- }
- }
- vector<vector<int>>nqueen(int n){
- vector<vector<int>>ans;
- vector<vector<int>>pattern(n,vector<int>(n,0));
- solve(ans,pattern,0,n);
- return ans;
- }
- int main() {
- int n;
- cin>>n;
- vector<vector<int>>ans=nqueen(n);
- for(auto x:ans){
- for(auto y:x)cout<<y<<" ";
- cout<<endl;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment