Problem solution · Python

Minimum Path Cost in a Hidden Grid

Minimum Path Cost in a Hidden Grid: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
64 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Minimum Path Cost in a Hidden Grid, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 64 lines of Python from the credited upstream file minimum-path-cost-in-a-hidden-grid.py.
  • The implementation visibly relies on hash lookup, ordered lookup, work queue.
  • No explicit loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMinimum Path Cost in a Hidden Grid · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(m * n * log(m * n))# Space: O(m * n) class GridMaster(object):    def canMove(self, direction):        pass     def move(self, direction):        pass     def isTarget(self):        pass  import collectionsimport heapq  class Solution(object):    def findShortestPath(self, master):        """        :type master: GridMaster        :rtype: int        """        directions = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)}        rollback = {'L': 'R', 'R': 'L', 'U': 'D', 'D': 'U'}         def dfs(pos, target, master, lookup, adj):            if target[0] is None and master.isTarget():                target[0] = pos            lookup.add(pos)            for d, (di, dj) in directions.iteritems():                if not master.canMove(d):                    continue                nei = (pos[0]+di, pos[1]+dj)                if nei in adj[pos]:                    continue                adj[pos][nei] = master.move(d)                if nei not in lookup:                    dfs(nei, target, master, lookup, adj)                adj[nei][pos] = master.move(rollback[d])                                def dijkstra(adj, start, target):            dist = {start:0}            min_heap = [(0, start)]            while min_heap:                curr, u = heapq.heappop(min_heap)                if dist[u] < curr:                    continue                for v, w in adj[u].iteritems():                    if v in dist and dist[v] <= curr+w:                        continue                    dist[v] = curr+w                    heapq.heappush(min_heap, (curr+w, v))            return dist[target] if target in dist else -1                 start = (0, 0)        target = [None]        adj = collections.defaultdict(dict)        dfs(start, target, master, set(), adj)        if not target[0]:            return -1        return dijkstra(adj, start, target[0]) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗