# 20BCS1313 CC Worksheet 9

```E
xperiment - 9
Branch: CSE
Semester: 5
Subject Name: COMPETITIVE CODING-I
UID: 20BCS1313
Section/Group: 20BCS-WM-903-A
Subject Code: 20CSP-314
● Aim/Overview of the practical: Implementation
of Hacker-rank questions.
Problem Statement 1:
Problem
Given a chess board having N&times;N cells, you need to place N queens on the board in such a way that no queen attacks
any other queen.
Input:
The only line of input consists of a single integer denoting N.
Output:
If it is possible to place all the N queens in such a way that no queen attacks another queen, then print N lines
having N integers. The integer in ith line and jth column will denote the cell (i,j) of the board and should be 1 if a queen
is placed at (i,j) otherwise 0. If there are more than way of placing queens print any of them. If it is not possible to place
all N queens in the desired way, then print &quot;Not possible&quot; (without quotes).
Code:
#20BCS1313
#include&lt;iostream&gt;
using namespace std;
bool issafe(int**arr, int x, int y, int n)
{
for(int row=0;row&lt;x;row++)
{
if(arr[row][y]==1)
{
return 0;
}
}
int row = x;
int col = y;
while(row&gt;=0&amp;&amp;col&gt;=0)
{
if(arr[row][col]==1)
{
return 0;
}
row--;
col--;
}
row = x;
col = y;
while(row&gt;=0&amp;&amp;col&lt;n){
if(arr[row][col]==1)
{
return 0;
}
row--;
col++;}
return 1;
}
bool nqueen(int**arr, int x, int n){
if(x&gt;=n)
{
return 1;
}
for(int col=0;col&lt;n;col++)
{
if (issafe(arr,x,col,n))
{
arr[x][col] = 1;
if(nqueen(arr, x+1,n))
{
return 1;
}
arr[x][col] = 0;
}
}
return 0;
}
int main(){
int n;
cin&gt;&gt;n;
int** arr = new int*[n];
for(int i=0;i&lt;n;i++)
{
arr[i] = new int[n];
for(int j=0;j&lt;n;j++)
{
arr[i][j]=0;
}
}
if(nqueen(arr,0,n))
{
for(int i=0;i&lt;n;i++){
for(int j=0;j&lt;n;j++)
{
cout&lt;&lt;arr[i][j]&lt;&lt;&quot; &quot;;
}
cout&lt;&lt;endl;
}
}
else{
cout&lt;&lt;&quot;Not possible&quot;&lt;&lt;endl;
}
}
OUTPUT:
Problem Statement 2:
CODE:
#20BCS1313
#include &lt;bits/stdc++.h&gt; using namespace std;
int solve(int n)
{
if (n &lt;= 1)
return 1; if (n == 2)
return 2; if (n == 3)
return 4;
return solve(n - 1) + solve(n - 2) + solve(n - 3);
}
int main()
{
int n; cin &gt;&gt; n;
cout &lt;&lt; &quot;No of ways to climb to &quot; &lt;&lt; n &lt;&lt; &quot; stairs: &quot;;
cout &lt;&lt; solve(n) &lt;&lt; endl; return 0;
}
OUTPUT:
Learning outcomes (What I have learnt):