forked from Vaani-pathariya/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKnight.cpp
97 lines (97 loc) · 3.53 KB
/
Knight.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include<bits/stdc++.h>
using namespace std;
int minStepToReachTarget(vector<int>KnightPos,vector<int>TargetPos,int n){
int ans =0;
queue<vector<int>>seq;
seq.push(KnightPos);
vector<vector<bool>>visited (n+1,vector<bool>(n+1,false));
visited[KnightPos[0]][KnightPos[1]]=true;
while (seq.size()>0){
int len=seq.size();
for (int i=0;i<len;i++){
vector<int>test =seq.front();
if (test[0]==TargetPos[0] && test[1]==TargetPos[1]){
return ans;
}
else {
if (test[0]+1<=n && test[1]+2<=n && !visited[test[0]+1][test[1]+2]){
vector<int>temp;
temp.push_back(test[0]+1);
temp.push_back(test[1]+2);
seq.push(temp);
visited[test[0]+1][test[1]+2]=true;
}
if (test[0]+1<=n && test[1]-2>=1 && !visited[test[0]+1][test[1]-2]){
vector<int>temp;
temp.push_back(test[0]+1);
temp.push_back(test[1]-2);
seq.push(temp);
visited[test[0]+1][test[1]-2]=true ;
}
if (test[0]-1>=1 && test[1]+2<=n && !visited[test[0]-1][test[1]+2]){
vector<int>temp;
temp.push_back(test[0]-1);
temp.push_back(test[1]+2);
seq.push(temp);
visited[test[0]-1][test[1]+2]=true;
}
if (test[0]-1>=1 && test[1]-2>=1 && !visited[test[0]-1][test[1]-2]){
vector<int>temp;
temp.push_back(test[0]-1);
temp.push_back(test[1]-2);
seq.push(temp);
visited[test[0]-1][test[1]-2]=true;
}
if (test[0]+2<=n && test[1]+1<=n && !visited[test[0]+2][test[1]+1]){
vector<int>temp;
temp.push_back(test[0]+2);
temp.push_back(test[1]+1);
seq.push(temp);
visited[test[0]+2][test[1]+1]=true ;
}
if (test[0]-2>=1 && test[1]+1<=n && !visited[test[0]-2][test[1]+1]){
vector<int>temp;
temp.push_back(test[0]-2);
temp.push_back(test[1]+1);
seq.push(temp);
visited[test[0]-2][test[1]+1]=true ;
}
if (test[0]-2>=1 && test[1]-1>=1 && !visited[test[0]-2][test[1]-1]){
vector<int>temp;
temp.push_back(test[0]-2);
temp.push_back(test[1]-1);
seq.push(temp);
visited[test[0]-2][test[1]-1]=true ;
}
if (test[0]+2<=n && test[1]-1>=1 && !visited[test[0]+2][test[1]-1]){
vector<int>temp;
temp.push_back(test[0]+2);
temp.push_back(test[1]-1);
seq.push(temp);
visited[test[0]+2][test[1]-1]=true;
}
seq.pop();
}
}
ans++;
}
}
int main(){
int n;
cin>>n;
vector<int>KnightPos;
vector<int>TargetPos;
//First Knight Pos
for (int i=0;i<2;i++){
int a;
cin>>a;
KnightPos.push_back(a);
}
for (int i=0;i<2;i++){
int a;
cin>>a;
TargetPos.push_back(a);
}
cout<<minStepToReachTarget(KnightPos,TargetPos,n);
return 0;
}