Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <bits/stdc++.h>
- using namespace std;
- bool Possible(char chess[][10], int row, int col, int n)
- {
- //checking in left diagonal
- int i,j;
- i=row-1;
- j=col-1;
- while(i>=0 && j>=0)
- {
- if(chess[i][j]=='Q')
- return false;
- i--;
- j--;
- }
- i=row-1;
- j=col+1; // see in ur code
- while(i>=0 && j<n)
- {
- if(chess[i][j]=='Q')
- return false;
- i--;
- j++;
- }
- i = row-1;
- j = col;
- while(i>=0)
- {
- if(chess[i][j]=='Q')
- return false;
- i--;
- }
- return true;
- }
- void placeNQueens(char chess[][10], int row,int n)
- {
- if(row==n)
- {
- for(int i=0 ; i<n ; i++)
- {
- for(int j=0 ; j<n ; j++)
- cout<<chess[i][j]<<"\t";
- cout<<"\n";
- }
- cout<<"\n";
- return;
- }
- for(int col=0 ; col<n ; col++)
- {
- // first check is it empty place or not
- if(chess[row][col]=='-' and Possible(chess,row,col,n)) // see in ur code
- {
- chess[row][col] = 'Q';
- placeNQueens(chess,row+1,n);
- chess[row][col] = '-';
- }
- }
- }
- void placeNQueens(int n)
- {
- char chess[10][10];
- memset(chess,'-',sizeof chess);
- placeNQueens(chess,0,n);
- }
- int main()
- {
- int n;
- // may be multiple testcase(question setter issue)
- while(cin>>n){
- if(n<=3 && n!=1)
- cout<<"Not Possible"<<"\n";
- else
- placeNQueens(n);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement