Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

HackerEarth N-Queens problem solution

YASH PAL, 31 July 2024
In this HackerEarth N-Queens problem solution, we have given a chessboard having N x N cells, you need to place N queens on the board in such a way that no queen attacks any other queen.
HackerEarth N-Queens problem solution

HackerEarth N-Queens problem solution.

#include<bits/stdc++.h>

using namespace std;
int mat[110][110]={0};
int n;
int state=0;
int attacked(int x, int y){
if(mat[x][y])return 1;
for(int i=1; i<=n; i++){

if(y-i >= 1 && mat[x][y-i])return 1;
if(y+i <= n && mat[x][y+i])return 1;
if(x-i >= 1 && mat[x-i][y])return 1;
if(x+i <= n && mat[x+i][y])return 1;
if(x-i >= 1 && y-i >= 1 && mat[x-i][y-i])return 1;
if(x+i <= n && y+i <= n && mat[x+i][y+i])return 1;
if(x+i <= n && y-i >= 1 && mat[x+i][y-i])return 1;
if(x-i >= 1 && y+i <= n && mat[x-i][y+i])return 1;
}
return 0;
}

void print(){
cout<<endl;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}

int solve(int x){
if(x == 0){
print();
return 1;
}
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
if(attacked(i, j) == 1)continue;
mat[i][j] = 1;
if(solve(x-1))return 1;
mat[i][j] = 0;
}
}
return 0;
}

int main(){
cin>>n;
if(solve(n))
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
else
cout<<"Not possiblen";
return 0;
}
coding problems

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes