Minimum steps to reach target by a Knight | Set 1
Given a square chessboard of N x N size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.
Explanation: In above diagram Knight takes 3 step to reach
from (4, 5) to (1, 1)
(4, 5) -> (5, 3) -> (3, 2) -> (1, 1)
Minimum steps to reach the target by a Knight using BFS:
To solve the problem follow the below idea:
This problem can be seen as the shortest path in an unweighted graph. Therefore we use BFS to solve this problem.
We try all 8 possible positions where a Knight can reach from its position. If the reachable position is not already visited and is inside the board, we push this state into the queue with a distance 1 more than its parent state. Finally, we return the distance of the target position, when it gets pop out from the queue
Below is the implementation of the above approach:
Time complexity: O(N2). In the worst case, all the cells will be visited
Auxiliary Space: O(N2). The nodes are stored in a queue.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Please Login to comment...