Problem Description
Given an infinite chess board, a knight starting at [0, 0] can make 8 possible moves. The goal is to determine the minimum number of moves needed for the knight to reach a target square [x, y]. The board spans from –infinity to +infinity, and it is guaranteed that a solution exists.
Key Insights
- Leverage the symmetry of the chessboard by converting target coordinates to their absolute values.
- Use a Breadth-First Search (BFS) because all moves have equal weight, ensuring the first encounter with the target is the minimal path.
- Prune the search space by only considering positions that are likely beneficial (e.g., positions having coordinates not far less than –1).
- Track visited states to avoid redundant processing.
- Optimize by bounding the search region relative to the target distance.
Space and Time Complexity
Time Complexity: O(n) where n is the number of positions processed during the BFS
Space Complexity: O(n) due to the storage requirements for the BFS queue and the visited set
Solution
We solve the problem using a BFS starting from the origin. First, normalize the target by taking the absolute value of x and y. BFS is then applied by exploring all eight possible knight moves at each step. Each move generates a new position that is enqueued if it hasn't been visited and falls within a reasonable bound (e.g., coordinates >= -1). The search terminates as soon as the target position is reached.