525. shortest-path-in-a-hidden-grid

You are given a hidden m x n grid with values 0 and 1, where 0 represents an empty cell, and 1 represents an obstacle. The starting position is at an unknown location in the grid. You can move up, down, left, or right but cannot move into obstacles or go out of bounds.

Your goal is to find the shortest path to the target, which is also located at an unknown position in the grid. You can only see the adjacent cells and determine whether they are obstacles or empty.

Write a function to find and return the shortest distance from the starting position to the target.

Example 1:

Input: grid = [[1,2],[-1,0]]

Output: 2

Explanation: One possible interaction is described below:

The robot is initially standing on cell (1, 0), denoted by the -1.

  • master.canMove('U') returns true.
  • master.canMove('D') returns false.
  • master.canMove('L') returns false.
  • master.canMove('R') returns false.
  • master.move('U') moves the robot to the cell (0, 0).
  • master.isTarget() returns false.
  • master.canMove('U') returns false.
  • master.canMove('D') returns true.
  • master.canMove('L') returns false.
  • master.canMove('R') returns true.
  • master.move('R') moves the robot to the cell (0, 1).
  • master.isTarget() returns true.
  • We now know that the target is the cell (0, 1), and the shortest path to the target cell is 2.

Example 2:

Input: grid = [[0,0,-1],[1,1,1],[2,0,0]]

Output: 4

Explanation: The minimum distance between the robot and the target cell is 4.

Now Your Turn!

Pick the correct output for the given input

Input: grid = [[-1,0],[0,2]]

Output: -1

Explanation: There is no path from the robot to the target cell.

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n, m <= 500
  • m == grid.length
  • n == grid[i].length
  • grid[i][j] is either -1, 0, 1, or 2.
  • There is exactly one -1 in grid.
  • There is exactly one 2 in grid.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* // This is the GridMaster's API interface.
* // You should not implement it, or speculate about its implementation
* class GridMaster {
* public:
* bool canMove(char direction);
* void move(char direction);
* boolean isTarget();
* };
*/
 
class Solution {
public:
int findShortestPath(GridMaster &master) {
//Your Code Goes Here
}
};
Test Case

Input:

Grid