Skip to main content

Minimum Path Cost in a Hidden Grid - Solution & Explanation

MediumPremiumFree on FleetCodeDepth-First SearchBreadth-First SearchGraphHeap (Priority Queue)16 min readAsked at: Meta, Google
Practice this problem

Problem Statement

This is an interactive problem.

There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and neither of them is blocked.

Each cell has a cost that you need to pay each time you move to the cell. The starting cell's cost is not applied before the robot moves.

You want to find the minimum total cost to move the robot to the target cell. However, you do not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the GridMaster object.

The GridMaster class has the following functions:

  • boolean canMove(char direction) Returns true if the robot can move in that direction. Otherwise, it returns false.
  • int move(char direction) Moves the robot in that direction and returns the cost of moving to that cell. If this move would move the robot to a blocked cell or off the grid, the move will be ignored, the robot will remain in the same position, and the function will return -1.
  • boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it returns false.

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 total cost to get the robot from its initial starting cell to the target cell. If there is no valid path between the cells, return -1.

Custom testing:

The test input is read as a 2D matrix grid of size m x n and four integers r1, c1, r2, and c2 where:

  • grid[i][j] == 0 indicates that the cell (i, j) is blocked.
  • grid[i][j] >= 1 indicates that the cell (i, j) is empty and grid[i][j] is the cost to move to that cell.
  • (r1, c1) is the starting cell of the robot.
  • (r2, c2) is the target cell of the robot.

Remember that you will not have this information in your code.

 

Example 1:

Input: grid = [[2,3],[1,1]], r1 = 0, c1 = 1, r2 = 1, c2 = 0
Output: 2
Explanation: One possible interaction is described below:
The robot is initially standing on cell (0, 1), denoted by the 3.
- master.canMove('U') returns false.
- master.canMove('D') returns true.
- master.canMove('L') returns true.
- master.canMove('R') returns false.
- master.move('L') moves the robot to the cell (0, 0) and returns 2.
- 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('D') moves the robot to the cell (1, 0) and returns 1.
- master.isTarget() returns true.
- master.move('L') doesn't move the robot and returns -1.
- master.move('R') moves the robot to the cell (1, 1) and returns 1.
We now know that the target is the cell (1, 0), and the minimum total cost to reach it is 2. 

Example 2:

Input: grid = [[0,3,1],[3,4,2],[1,2,0]], r1 = 2, c1 = 0, r2 = 0, c2 = 2
Output: 9
Explanation: The minimum cost path is (2,0) -> (2,1) -> (1,1) -> (1,2) -> (0,2).

Example 3:

Input: grid = [[1,0],[0,1]], r1 = 0, c1 = 0, r2 = 1, c2 = 1
Output: -1
Explanation: There is no path from the robot to the target cell.

 

Constraints:

  • 1 <= n, m <= 100
  • m == grid.length
  • n == grid[i].length
  • 0 <= grid[i][j] <= 100

Approach Overview

Problem Overview: The grid is hidden and can only be explored through an interactive API that allows movement and returns the cost of entering a cell. Your task is to discover the grid structure and compute the minimum path cost from the start cell to the target cell.

Approach 1: DFS Graph Construction + Heap-Optimized Dijkstra (O(V log V) time, O(V) space)

The grid is unknown at the start, so the first step is exploration. Use Depth-First Search to move through every reachable cell while backtracking to the previous position after exploring each direction. During this exploration, record each cell as a node in a graph and store edges with their movement cost. The DFS effectively converts the hidden grid into a standard weighted graph.

Once the graph is built, run Dijkstra’s shortest path algorithm using a min-heap from Heap (Priority Queue). Initialize the start node with cost 0 and repeatedly expand the node with the smallest accumulated cost. Each edge relaxation updates neighbor distances when a cheaper path is found. This guarantees the optimal path cost to the target because all edge weights are non‑negative.

The key insight is separating the problem into two phases: discovery and optimization. DFS handles the unknown environment while maintaining the correct position using backtracking moves. Dijkstra then works on the discovered graph to compute the true minimum cost efficiently. Time complexity is O(V log V) due to heap operations during shortest path computation, and space complexity is O(V) for storing visited nodes, graph edges, and distances.

Approach 2: DFS Graph Construction + BFS (O(V + E) time, O(V) space)

After building the graph with DFS, you could run Breadth-First Search to find the shortest path if all movement costs were identical. BFS explores nodes level by level and guarantees the minimum number of steps. However, this problem assigns different entry costs to cells, so BFS does not produce the correct minimum-cost path. It’s mainly useful as a conceptual baseline for understanding why a weighted shortest-path algorithm is required.

Recommended for interviews: The DFS exploration followed by Dijkstra’s algorithm is the expected solution. Interviewers want to see that you recognize two separate challenges: discovering the hidden grid and computing a weighted shortest path. Demonstrating DFS with careful backtracking shows control over the interactive environment, while implementing heap-based Dijkstra proves you understand optimal graph traversal for weighted edges.

Solution

We observe that the grid size is m times n, where m, n leq 100. Therefore, we can initialize the starting coordinates as (sx, sy) = (100, 100) and assume the grid size is 200 times 200. Then, we can use depth-first search (DFS) to explore the entire grid and construct a 2D array g representing the grid, where g[i][j] represents the movement cost from the starting point (sx, sy) to coordinates (i, j). If a cell is unreachable, we set its value to -1. We store the target coordinates in target, and if the target cannot be reached, then target = (-1, -1).

Next, we can use the heap-optimized Dijkstra algorithm to calculate the minimum cost path from the starting point (sx, sy) to the target target. We use a priority queue to store the current path cost and coordinates, and use a 2D array dist to record the minimum cost from the starting point to each cell. When we pop a node from the priority queue, if that node is the target, we return the current path cost as the answer. If the path cost of that node is greater than the value recorded in dist, we skip that node. Otherwise, we traverse the four neighbors of that node. If a neighbor is reachable and the path cost to reach the neighbor through this node is smaller, we update the neighbor's path cost and add it to the priority queue.

The time complexity is O(m times n log(m times n)), and the space complexity is O(m times n). Where m and n are the number of rows and columns in the grid, respectively.

Code

Python

Java

C++

JavaScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
DFS Exploration + Dijkstra (Priority Queue)O(V log V)O(V)General case with weighted movement costs in the hidden grid
DFS Exploration + BFSO(V + E)O(V)Only valid if every move has identical cost
DFS Exploration + A* SearchO(E log V)O(V)Possible optimization when a heuristic to the target is known

Video Solution

1810. Minimum Path Cost in a Hidden Grid (Leetcode Medium)Programming Live with Larry497 views views

Watch 2 more video solutions →

Frequently Asked Questions

Is Minimum Path Cost in a Hidden Grid easy or hard?
The problem is rated Medium but feels harder because it combines an interactive environment with graph algorithms. Candidates must correctly backtrack during DFS exploration and then apply Dijkstra’s algorithm to compute the minimum weighted path.
Minimum Path Cost in a Hidden Grid Python/Java solution
Implement the solution in two phases. First, perform DFS with backtracking using the interactive API to map reachable cells and record edge costs. Second, run Dijkstra’s algorithm using a priority queue to compute the minimum cost path to the target. This approach works the same in Python, Java, C++, and JavaScript.
How to solve Minimum Path Cost in a Hidden Grid in O(n)?
An O(n) approach is not generally possible because the grid edges have different weights. The correct strategy builds the grid with DFS and then applies Dijkstra’s shortest path algorithm, which requires a priority queue and results in O(V log V) time complexity.
What is the best approach for Minimum Path Cost in a Hidden Grid?
The most effective solution first explores the hidden grid using Depth-First Search and records all reachable cells as a graph. After the graph is discovered, Dijkstra’s algorithm with a priority queue computes the minimum cost path to the target. This approach handles weighted movement costs and runs in O(V log V) time.
Is Minimum Path Cost in a Hidden Grid asked at Google/Amazon/Meta?
Hidden grid and interactive pathfinding problems are commonly associated with Google-style interviews because they test graph exploration and shortest path reasoning. Variants also appear in Amazon and Meta interview prep sets focusing on DFS, graph traversal, and Dijkstra’s algorithm.
What data structure is used in Minimum Path Cost in a Hidden Grid?
The solution uses several structures: a graph representation for discovered cells, a visited set for DFS exploration, and a min-heap (priority queue) for Dijkstra’s algorithm. The heap ensures that the node with the smallest current cost is processed first.
What is the time complexity of Minimum Path Cost in a Hidden Grid?
The optimal solution runs in O(V log V) time. DFS exploration visits each reachable cell once to construct the graph, and Dijkstra’s algorithm processes nodes using a priority queue, leading to the logarithmic factor. Space complexity is O(V) for storing the discovered graph and distance map.

Ready to solve this problem?

Practice Minimum Path Cost in a Hidden Grid with our built-in code editor and test cases.

Practice on FleetCode