Minimum Path Cost in a Hidden Grid — LeetCode 1810 Python Solution

MediumLeetCode PremiumDepth-First SearchBreadth-First SearchGraphArrayInteractiveMatrixShortest PathHeap (Priority Queue)
Problem
#1810
Reading time
11 min

The problem

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.

Example

Input
grid = [[2,3],[1,1]], r1 = 0, c1 = 1, r2 = 1, c2 = 0
Output
2
Explanation
One possible interaction is described below:

Python solution

Python
# """
# This is GridMaster's API interface.
# You should not implement it, or speculate about its implementation
# """
# class GridMaster(object):
#    def canMove(self, direction: str) -> bool:
#
#
#    def move(self, direction: str) -> int:
#
#
#    def isTarget(self) -> bool:
#
#


class Solution(object):
    def findShortestPath(self, master: "GridMaster") -> int:
        def dfs(x: int, y: int) -> None:
            nonlocal target
            if master.isTarget():
                target = (x, y)
            for k in range(4):
                dx, dy = dirs[k], dirs[k + 1]
                nx, ny = x + dx, y + dy
                if (
                    0 <= nx < m
                    and 0 <= ny < n
                    and g[nx][ny] == -1
                    and master.canMove(s[k])
                ):
                    g[nx][ny] = master.move(s[k])
                    dfs(nx, ny)
                    master.move(s[(k + 2) % 4])

        dirs = (-1, 0, 1, 0, -1)
        s = "URDL"
        m = n = 200
        g = [[-1] * n for _ in range(m)]
        target = (-1, -1)
        sx = sy = 100
        dfs(sx, sy)
        if target == (-1, -1):
            return -1
        pq = [(0, sx, sy)]
        dist = [[inf] * n for _ in range(m)]
        dist[sx][sy] = 0
        while pq:
            w, x, y = heappop(pq)
            if (x, y) == target:
                return w
            for dx, dy in pairwise(dirs):
                nx, ny = x + dx, y + dy
                if (
                    0 <= nx < m
                    and 0 <= ny < n
                    and g[nx][ny] != -1
                    and w + g[nx][ny] < dist[nx][ny]
                ):
                    dist[nx][ny] = w + g[nx][ny]
                    heappush(pq, (dist[nx][ny], nx, ny))
        return -1

Complexity

MeasureComplexity
TimeO(m \times n \log(m \times n))
SpaceO(m \times n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1810. Minimum Path Cost in a Hidden Grid is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1810. Minimum Path Cost in a Hidden Grid?
LeetCode 1810. Minimum Path Cost in a Hidden Grid is rated Medium on LeetCode.
What is the time complexity of LeetCode 1810. Minimum Path Cost in a Hidden Grid?
The Python solution on this page runs in O(m \times n \log(m \times n)).
What is the space complexity of LeetCode 1810. Minimum Path Cost in a Hidden Grid?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1810. Minimum Path Cost in a Hidden Grid cover?
LeetCode 1810. Minimum Path Cost in a Hidden Grid is tagged Depth-First Search, Breadth-First Search, Graph, Array, Interactive, Matrix, Shortest Path and Heap (Priority Queue) on LeetCode.
Is LeetCode 1810. Minimum Path Cost in a Hidden Grid a premium problem?
Yes. LeetCode 1810. Minimum Path Cost in a Hidden Grid is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview