Skip to content

Commit ad10c58

Browse files
add implementation for copy constructor in House class and knight's tour problem using backtracking
1 parent 8fd1590 commit ad10c58

File tree

6 files changed

+85
-7
lines changed

6 files changed

+85
-7
lines changed

20OOPS/copy_construct.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
class House{
4+
public:
5+
int price;
6+
string* name;
7+
House(int p, string n){
8+
price = p;
9+
name = new string(n);
10+
}
11+
House(const House& other){
12+
price = other.price;
13+
name = new string(*other.name);
14+
}
15+
~House(){
16+
delete name;
17+
}
18+
void showDetails(){
19+
cout<< *(name) <<" sold for "<<price<<endl;
20+
}
21+
};
22+
int main(){
23+
House h1(45, "Arnayak");
24+
h1.showDetails();
25+
26+
House h2 = h1;
27+
h2.showDetails();
28+
29+
*h1.name = "Villa";
30+
h1.showDetails();
31+
32+
h2.showDetails();
33+
}

20OOPS/copy_construct.exe

141 KB
Binary file not shown.

32backtracking/03knightstour.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include<iostream>
2+
#include<vector>
3+
using namespace std;
4+
5+
bool canGo(vector<vector<int>> &grid, int n, int i, int j){
6+
return i>=0 and j>=0 and i<n and j<n and grid[i][j]==-1;
7+
}
8+
9+
vector<int> dx{-2, -1, -2, -1, +2, +1, +2, +1};
10+
vector<int> dy{+1, +2, -1, -2, +1, +2, -1, -2};
11+
12+
void display(vector<vector<int>>& grid,int n){
13+
for(int i=0;i<n;i++){
14+
for(int j=0;j<n; j++){
15+
cout<<grid[i][j]<<"\t";
16+
}
17+
cout<<"\n";
18+
}
19+
cout<<endl;
20+
}
21+
22+
void func(vector<vector<int>>& grid, int i, int j, int n, int count){
23+
if(count == n*n - 1){
24+
//last position
25+
grid[i][j] = count;
26+
display(grid, n);
27+
grid[i][j] = -1;
28+
return;
29+
}
30+
//8 moves in total for a knight
31+
// top left & right , bottom left & right
32+
33+
for(int k=0;k<8;k++){
34+
if(canGo(grid, n, i + dx[k], j + dy[k])){
35+
grid[i][j] = count;
36+
func(grid, i + dx[k], j + dy[k], n, count+1);
37+
grid[i + dx[k]][j + dy[k]] = -1;
38+
}
39+
}
40+
41+
}
42+
43+
void knightTour(int n, int i, int j){
44+
vector<vector<int>> grid(n, vector<int> (n, -1));
45+
func(grid, i, j, n, 0);
46+
}
47+
48+
int main(){
49+
knightTour(5, 0, 0);
50+
return 0;
51+
}

32backtracking/03knightstour.exe

173 KB
Binary file not shown.

sample.cpp

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
11
#include<bits/stdc++.h>
22
using namespace std;
3-
/*
4-
Simple file for doing a local run for lC questions*/
5-
class Solution{
6-
7-
};
8-
93
int main(){
10-
4+
return 0;
115
}

sample.exe

-67.2 KB
Binary file not shown.

0 commit comments

Comments
 (0)