Meesho Coding Question – Solved

12 Live
The city of Hackerland can be represented using a grid with n rows and m columns containing an empty cell represented by a '*' and a blocked cell represented by a #. Traveling is allowed only through empty cells. The people of Hackerland are required to travel from a starting cell defined by the character 'S' to an ending cell represented by a character 'E'. The people can jump a length of any integer k in all four directions from a given cell i.e. up, down, left, and right. However, if the jump length kis greater than 1, the next jump must be made in the same direction, For example, a hacker is allowed to jump 3 units towards the right, followed by 1 unit towards the right, and then 3 units towards the left. They however cannot jump 3 units towards the right followed by 1 unit towards the left as direction change is not allowed if the previous jump was of length greater than 1. Note that the last jump in any jump sequence is always of length 1. The jump can be made over a blocked cell as well as long as both starting and ending cells are empty. Given the map of Hackerland as a 2g matrix grid, that contains exactly one 'S' and 'E' each, find the minimum number of jumps required to travel from Sto E. Report -1 if it is not possible to reach E from S. Example Suppose n = 5, m = 6 and grid = ["S **** #". ******** ******* ******** " ***** E")

Asked in: Meesho

Image of the Question

Question Image

All Testcases Passed ✔



Passcode Image

Solution


import heapq
def getMinJumps(grid):
    n,m = len(grid), len(grid[0])
    dist = [[float('inf') for i in range(m)] for j in range(n)] 
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
To solve this problem, the goal is to determine the minimum number of valid jumps required to move from the start cell 'S' to the end cell 'E' on a 2D grid. Movement is constrained by rules about jump length and direction. Specifically, from any current position, a hacker can jump any positive integer distance `k` in any of the four cardinal directions (up, down, left, right), but with a catch: if a jump is made with `k > 1`, the next jump must continue in the same direction until a jump of length 1 resets the movement direction.

This unique constraint transforms what would normally be a straightforward grid traversal problem into one that requires additional state tracking: not just the current position on the grid, but also the direction of movement and whether the previous jump was of length greater than 1.

Let’s break this problem into key components and describe the conceptual approach to solving it.

1. **Grid Parsing and Setup**:
Begin by scanning the grid to identify the coordinates of the starting position 'S' and the ending position 'E'. This setup is essential before initiating any form of traversal. The grid itself is composed of open cells (`*`), blocked cells (`#`), and the start/end points. It’s also helpful to standardize these character values into a form that can be used programmatically, treating 'S' and 'E' as open cells for the purpose of movement.

2. **State Representation**:
Unlike typical shortest-path problems, the state here isn’t just a position `(x, y)` but includes additional components: the last direction of movement (if any) and a flag or counter to indicate whether the last jump was of length greater than 1. This is necessary because the allowed next moves depend on this state — you can only change direction if the previous jump was of length 1.

3. **Valid Move Calculation**:
From any given position, you can try to jump in all four directions. For each direction:
- Attempt jump lengths starting from 1 up to the maximum possible in that direction until a wall (`#`) or grid boundary is reached.
- For each jump, check if the destination cell is walkable (i.e., not blocked).
- If the jump is of length 1, mark that as a reset of directional constraint — you can now change direction on your next move.
- If the jump is longer than 1, you must continue moving in that direction in the next jump.

4. **Search Strategy**:
Since the problem asks for the minimum number of jumps, a Breadth-First Search (BFS) approach is most suitable. In BFS, you explore the grid level by level, which ensures that when you first reach the end cell 'E', you’ve done so using the minimal number of jumps.

In your BFS queue, each state should include:
- The current coordinates (x, y)
- The direction of movement (or `null` if none yet)
- A flag indicating whether the previous jump was of length greater than 1
- The current count of jumps made so far

You should also maintain a visited set or matrix to avoid revisiting the same state, taking into account not just position but direction and movement status.

5. **Handling Constraints**:
The challenge is primarily in respecting the movement constraint that after a jump of length > 1, direction must remain the same. This requires careful state propagation. Every time you make a move, ensure that you check whether changing direction is allowed based on your last jump.

6. **Termination and Result**:
As you perform BFS, the moment you reach the destination cell 'E', return the number of jumps taken to get there. If BFS completes without reaching 'E', return -1 indicating that there is no valid path from 'S' to 'E' under the given constraints.

7. **Efficiency Consideration**:
Since you might explore the same cell multiple times with different movement directions and jump histories, the visited structure must reflect all three components: position, direction, and jump continuity. Without this, you may either revisit too much or prune valid paths incorrectly.

This approach ensures that all valid paths are explored while adhering to the special directional constraints, and that the shortest path is selected thanks to the nature of BFS. By treating the movement rules as part of the state and traversing the grid accordingly, you can handle both simple and complex grid layouts effectively.
```


Related Questions