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.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- 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.
Use this to learn the idea, then write your own version.
123 4class GridMaster(object):5 def canMove(self, direction):6 pass7 8 def move(self, direction):9 pass10 11 def isTarget(self):12 pass13 14 15import collections16import heapq17 18 19class Solution(object):20 def findShortestPath(self, master):21 """22 :type master: GridMaster23 :rtype: int24 """25 directions = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)}26 rollback = {'L': 'R', 'R': 'L', 'U': 'D', 'D': 'U'}27 28 def dfs(pos, target, master, lookup, adj):29 if target[0] is None and master.isTarget():30 target[0] = pos31 lookup.add(pos)32 for d, (di, dj) in directions.iteritems():33 if not master.canMove(d):34 continue35 nei = (pos[0]+di, pos[1]+dj)36 if nei in adj[pos]:37 continue38 adj[pos][nei] = master.move(d)39 if nei not in lookup:40 dfs(nei, target, master, lookup, adj)41 adj[nei][pos] = master.move(rollback[d])42 43 def dijkstra(adj, start, target):44 dist = {start:0}45 min_heap = [(0, start)]46 while min_heap:47 curr, u = heapq.heappop(min_heap)48 if dist[u] < curr:49 continue50 for v, w in adj[u].iteritems():51 if v in dist and dist[v] <= curr+w:52 continue53 dist[v] = curr+w54 heapq.heappush(min_heap, (curr+w, v))55 return dist[target] if target in dist else -1 56 57 start = (0, 0)58 target = [None]59 adj = collections.defaultdict(dict)60 dfs(start, target, master, set(), adj)61 if not target[0]:62 return -163 return dijkstra(adj, start, target[0])64