ShareChat Coding Question – Solved

7 Live
1. Question 1 Given a chessboard of n rows (top to bottom) and n columns (left to right). In each move, a knight moves either: 2 column positions and 1 row position 2 row positions and 1 column position In other words, a move is 2 steps along one axis and 1 step along a perpendicular axis. Given a starting position A and ending position B, calculate the minimum number of moves needed by the knight to move from A to B if it is possible. If it is not possible, return -1. All moves must remain within the chessboard. Example n = 9 startRow = 4 startCol = 4 endRow = 4 endCol = 8 The chessboard has a size of 9 x 9. Starts at the position (startRow, startCol) = (4, 4). - Move 1 step up or down, then 2 steps right to reach either the position (3,6) or (5,6). - Move 2 steps right and 1 step down or up as...

Asked in: ShareChat

Image of the Question

Question Image

All Testcases Passed ✔



Passcode Image

Solution


from collections import deque
def minMoves(n, startRow, startCol, endRow, endCol):
    visited = set()
    q = deque()
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
To solve the problem of finding the minimum number of moves a knight needs to travel from a starting position to an ending position on an n x n chessboard, you need to understand the unique movement capabilities of the knight and then use a methodical approach to explore the board for the shortest path.

Step 1: Understand the knight’s movement constraints
- A knight moves in an “L” shape: either 2 steps along one axis and 1 step along the perpendicular axis.
- Specifically, from any position (r, c), the knight can move to any of up to 8 possible positions:
- (r + 2, c + 1), (r + 2, c - 1)
- (r - 2, c + 1), (r - 2, c - 1)
- (r + 1, c + 2), (r + 1, c - 2)
- (r - 1, c + 2), (r - 1, c - 2)
- Some of these positions may fall outside the board boundaries; these moves are invalid.

Step 2: Clarify the goal
- The objective is to find the minimum number of moves (the shortest path) to reach the target cell from the start cell.
- If the target cannot be reached due to board boundaries or unreachable configurations, return -1.

Step 3: Model the problem as a shortest path in a grid
- The chessboard can be represented as a graph where each cell is a node.
- Edges exist between nodes if a knight can move from one cell to the other in a single move.
- The problem reduces to finding the shortest path from the start node to the end node in this graph.

Step 4: Select an appropriate search algorithm
- Since all moves have equal cost (each move counts as 1), a Breadth-First Search (BFS) is well-suited.
- BFS explores nodes level-by-level and guarantees the shortest path in an unweighted graph.

Step 5: Implement BFS traversal
- Initialize a queue and add the starting position.
- Keep track of visited positions to avoid cycles and repeated visits.
- Maintain a distance or move count for each visited cell.
- While the queue is not empty, dequeue the current position and examine all valid knight moves from there.
- For each valid move, if it has not been visited, enqueue it and record its distance as current distance + 1.
- If the target position is reached during the traversal, return the distance immediately as the minimum moves.

Step 6: Handle edge cases and invalid inputs
- If the starting position is the same as the ending position, the minimum moves is zero.
- Ensure that start and end positions are valid positions within the chessboard.
- Return -1 if BFS completes without reaching the target, indicating the target is unreachable.

Step 7: Optimize space and time
- Use a 2D visited array or set to track visited positions efficiently.
- Avoid recomputing moves that go off the board.
- Since the chessboard size is n x n, BFS complexity is O(n^2) in the worst case, which is reasonable for moderate n.

Step 8: Testing and validation
- Test the algorithm on small boards where the knight’s shortest path is known.
- Test cases where start and end positions are the same.
- Cases where the target is at the edge or corner of the board.
- Cases where no valid path exists (should return -1).
- Larger boards to ensure performance holds.

Step 9: Visualize the path (optional)
- If required, reconstruct the actual path by storing predecessors during BFS traversal.
- This can help in debugging or providing more insights.

Summary:
- Represent the board as a graph where each cell is a node.
- Use BFS starting from the start position to find the shortest path.
- Explore all valid knight moves from each position.
- Track visited positions to avoid infinite loops.
- Return the number of moves upon reaching the end, or -1 if unreachable.

By carefully modeling the problem and applying BFS with appropriate boundary checks and bookkeeping, you can efficiently determine the minimum number of knight moves required on an n x n chessboard.
```


Related Questions