Skip to content

Commit 642d7f6

Browse files
authored
created knight move
1 parent e89665c commit 642d7f6

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Steps by Knight

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
int main(){
4+
5+
int N, a, b, c;
6+
cin>>N>>a>>b>>c;
7+
int knightPos[] = {a, b};
8+
int targetPos[] = {c, d};
9+
cout<< minStepToReachTarget(knightPos, targetPos, N);
10+
}
11+
12+
int minStepToReach(int knightX, int knightY, int targetX, int targetY, int N) {
13+
if (knightX == targetX && knightY == targetY) return 0;
14+
15+
int visited[N + 1][N + 1] = {0};
16+
visited[knightX][knightY] = 1;
17+
18+
queue<pair<int, int> > q;
19+
//q.push(pair<int, int>(knightX, knightY));
20+
q.push({knightX, knightY});
21+
int rr[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
22+
int cc[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
23+
//travelling bfs to find all position a knight can take
24+
while (!q.empty()) {
25+
int r = q.front().first;
26+
int c = q.front().second;
27+
q.pop();
28+
29+
for (int i = 0; i < 8; i++) {
30+
int nextr = r + rr[i];
31+
int nextc = c + cc[i];
32+
33+
if (nextr < 1 || nextc < 1 || nextr > N || nextc > N) continue;
34+
if (visited[nextr][nextc] != 0) continue;
35+
if (nextr == targetX && nextc == targetY)
36+
return visited[r][c];
37+
visited[nextr][nextc] = visited[r][c] + 1;
38+
q.push(pair<int, int>(nextr, nextc));
39+
}
40+
}
41+
//return visited[targetX][targetY] - 1;
42+
}
43+
int minStepToReachTarget(int k[], int T[], int n){
44+
return minStepToReach(k[0], k[1], T[0], T[1], n);
45+
}

0 commit comments

Comments
 (0)