LeetCode 1778. Shortest Path in a Hidden Grid
DFS+BFS
This is an interactive problem.
You are given a robot in a hidden grid, and it wants to go to a target cell in this grid. The grid is of size m x n, and each cell in the grid can be empty or blocked. It is guaranteed that the start point and the robot's destination are different, and neither of them is blocked.
You want to find the robot's minimum distance to the target cell. However, you do not know the grid's dimensions, or the starting point of the robot, or its target destination. You are only allowed to ask queries to your GridMaster object.
You are given a class GridMaster which you can call the following functions from:
boolean GridMaster.canMove(char direction)returnstrueif the robot can move in that direction. Otherwise, it returnsfalse.void GridMaster.move(char direction)moves the robot in that direction. If this move would move the robot to a blocked cell or off the grid, it will be ignored, and the robot would remain in the same position.boolean GridMaster.isTarget()returnstrueif the robot is currently on the target cell. Otherwise, it returnsfalse.
Note that direction in the above functions should be a character from {'U','D','L','R'}, representing the directions up, down, left, and right, respectively.
Return the minimum distance between the robot's initial starting cell and the target cell if there is a path between them. Otherwise, return -1.
Custom testing:
The test input is read as a 2D matrix grid of size m x n where:
grid[i][j] == -1indicates that the robot is in cell(i, j).grid[i][j] == 0indicates that the cell(i, j)is blocked.grid[i][j] == 1indicates that the cell(i, j)is empty.grid[i][j] == 2indicates that the cell(i, j)is the target cell.
There is exactly one -1 and 2 in grid. Remember that you will not have this information in your code.
Example 1:
Example 2:
Example 3:
Constraints:
m == grid.lengthn == grid[i].length1 <= n, m <= 500grid[i][j]is either-1,0,1, or2.There is exactly one
-1ingrid.There is exactly one
2ingrid.
Solution:
Last updated
Was this helpful?