|
| 1 | +// { Driver Code Starts |
| 2 | +#include<bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | + // } Driver Code Ends |
| 6 | + |
| 7 | +class Node { |
| 8 | + public: |
| 9 | + int x, y, distance; |
| 10 | + Node(int x, int y, int dist) : x(x), y(y), distance(dist) {} |
| 11 | +}; |
| 12 | + |
| 13 | +class Solution |
| 14 | +{ |
| 15 | + bool isInsideBoard(int x, int y, int N) { |
| 16 | + return (x >= 1 and x <= N and y >= 1 and y <= N); |
| 17 | + } |
| 18 | + |
| 19 | + public: |
| 20 | + //Function to find out minimum steps Knight needs to reach target position. |
| 21 | + int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N) |
| 22 | + { |
| 23 | + // Code here |
| 24 | + |
| 25 | + queue<Node> q; |
| 26 | + |
| 27 | + // generate first 4 pairs .... |
| 28 | + // and then invert for next 4 pairs |
| 29 | + int dx[8] = {-2, -2, 2, 2, -1, 1, -1, 1}; |
| 30 | + int dy[8] = {-1, 1, -1, 1, -2, -2, 2, 2}; |
| 31 | + |
| 32 | + vector<vector<bool> > visited(N + 1, vector<bool>(N + 1, false)); |
| 33 | + |
| 34 | + q.push(Node(KnightPos[0], KnightPos[1], 0)); |
| 35 | + |
| 36 | + visited[KnightPos[0]][KnightPos[1]] = true; |
| 37 | + |
| 38 | + while(!q.empty()) { |
| 39 | + |
| 40 | + // grab front and pop |
| 41 | + Node current = q.front(); |
| 42 | + q.pop(); |
| 43 | + |
| 44 | + // exit condition |
| 45 | + if(current.x == TargetPos[0] and current.y == TargetPos[1]) return current.distance; |
| 46 | + |
| 47 | + // push neighbors |
| 48 | + for(int i = 0; i < 8; i++) { |
| 49 | + int nx = current.x + dx[i]; |
| 50 | + int ny = current.y + dy[i]; |
| 51 | + |
| 52 | + if(isInsideBoard(nx, ny, N) and !visited[nx][ny]) { |
| 53 | + visited[nx][ny] = true; |
| 54 | + q.push(Node(nx, ny, current.distance + 1)); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + return -1; // knight unreachable to its target |
| 59 | + } |
| 60 | +}; |
| 61 | + |
| 62 | +// { Driver Code Starts. |
| 63 | +int main(){ |
| 64 | + int tc; |
| 65 | + cin >> tc; |
| 66 | + while(tc--){ |
| 67 | + vector<int>KnightPos(2); |
| 68 | + vector<int>TargetPos(2); |
| 69 | + int N; |
| 70 | + cin >> N; |
| 71 | + cin >> KnightPos[0] >> KnightPos[1]; |
| 72 | + cin >> TargetPos[0] >> TargetPos[1]; |
| 73 | + Solution obj; |
| 74 | + int ans = obj.minStepToReachTarget(KnightPos, TargetPos, N); |
| 75 | + cout << ans <<"\n"; |
| 76 | + } |
| 77 | + return 0; |
| 78 | +} // } Driver Code Ends |
0 commit comments