Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerEarth N-Queens problem solution

YASH PAL, 31 July 202413 February 2026
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 solutions HackerEarth HackerEarth

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes