Grid Traversal (Infrastructure Automation Internship)
The city of Hackerland is represented by a grid with n rows and m columns, where empty cells are marked with "*", and blocked cells are marked with '#'. Travel is only possible through empty cells. The inhabitants need to travel from a starting cell marked by 'S' to an ending cell marked by 'E'.
They can jump any integer length k in four directions: up, down, left, and right. If the jump length k is greater than 1, the next jump must continue in the same direction. For example, a hacker can jump 3 units to the right, followed by 1 unit to the right, and then 3 units to the left. However, they cannot jump 3 units to the right followed by 1 unit to the left, as direction changes are not allowed if the previous jump was longer than 1 unit. The last jump in any sequence must always be of length 1. Jumps can be made over blocked cells as long as both the starting and ending cells of the jump are empty.
Given the map of Hackerland as a 2D matrix grid containing exactly one 'S' and one 'E', determine the minimum number of jumps required to travel from 'S' to 'E'. Return -1 if it is not possible.
Complete the function getMinJumps in the editor with the following parameter(s):
- grid[n][m]: an array of strings
Returns
int: the minimum number of jumps to reach cell 'E' starting from 'S', or -1 if it is not possible
Constraints
1Example 1
2Example 2
The optimal path is:
- Jump from (0, 0) to (0, 5). The next jump needs to be in the same direction.
- Jump from (0, 5) to (0, 6).
- Jump from (0, 6) to (2, 6). The next jump must be in the same direction.
- Jump from (2, 6) to (3, 6). We have reached the destination cell.
Thus, we need 4 moves.
3Example 3
