Uploaded by Saiyam Kaul

20BCS1313 CC Worksheet 9

advertisement
E
xperiment - 9
Student Name: Swarnim Aditya Pandey
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×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 "Not possible" (without quotes).
Code:
#Swarnim Aditya Pandey
#20BCS1313
#include<iostream>
using namespace std;
bool issafe(int**arr, int x, int y, int n)
{
for(int row=0;row<x;row++)
{
if(arr[row][y]==1)
{
return 0;
}
}
int row = x;
int col = y;
while(row>=0&&col>=0)
{
if(arr[row][col]==1)
{
return 0;
}
row--;
col--;
}
row = x;
col = y;
while(row>=0&&col<n){
if(arr[row][col]==1)
{
return 0;
}
row--;
col++;}
return 1;
}
bool nqueen(int**arr, int x, int n){
if(x>=n)
{
return 1;
}
for(int col=0;col<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>>n;
int** arr = new int*[n];
for(int i=0;i<n;i++)
{
arr[i] = new int[n];
for(int j=0;j<n;j++)
{
arr[i][j]=0;
}
}
if(nqueen(arr,0,n))
{
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Not possible"<<endl;
}
}
OUTPUT:
Problem Statement 2:
CODE:
#Swarnim Aditya Pandey
#20BCS1313
#include <bits/stdc++.h> using namespace std;
int solve(int n)
{
if (n <= 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 >> n;
cout << "No of ways to climb to " << n << " stairs: ";
cout << solve(n) << endl; return 0;
}
OUTPUT:
Learning outcomes (What I have learnt):
1. Learn about backtracking.
Download