You control a robot in a mysterious hidden grid where each cell has a movement cost and you need to find the minimum cost path to reach a target destination!
This is an interactive problem - you don't know the grid layout, dimensions, starting position, or target location upfront. Instead, you must explore the grid using a GridMaster API:
canMove(direction) - Check if robot can move in direction ('U', 'D', 'L', 'R')
move(direction) - Move robot and return the cost of the destination cell (-1 if blocked)
isTarget() - Check if current cell is the target
Each cell is either empty (with a positive movement cost) or blocked. The starting cell's cost doesn't count - only cells you move into have costs applied.
Goal: Return the minimum total cost to reach the target, or -1 if impossible.
Challenge: You must first explore and map the grid using DFS/BFS, then find the shortest weighted path using Dijkstra's algorithm!
π‘ Note:The robot explores the grid using DFS, mapping all accessible cells and their costs. Then Dijkstra's algorithm finds the minimum cost path: (0,0)β(0,1)β(1,1)β(2,2)β(3,3) with total cost 0+1+2+1+1=5. Note: starting cell cost doesn't count, so actual path cost is 1+2+1+2=6.
π‘ Note:Some cells are blocked (value 0), so the robot must find an alternative path. After DFS exploration, Dijkstra finds the optimal route avoiding blocked cells: (0,0)β(1,0)β(2,0)β(2,1)β(2,2)β(2,3) with minimum total cost of 8.
π‘ Note:The target cell is completely surrounded by blocked cells (0s), making it unreachable from the starting position. DFS exploration confirms no path exists, so the function returns -1.
Time & Space Complexity
Time Complexity
β±οΈ
O((V + E) log V)
DFS exploration O(V + E) plus Dijkstra's algorithm O((V + E) log V) where V is cells and E is connections
n
2n
β‘ Linearithmic
Space Complexity
O(V)
Store the grid map, priority queue, and distance array
Grid cells contain values 0 (blocked) or 1-1000 (movement cost)
Starting and target cells are guaranteed to be different and unblocked
Robot can only move in 4 directions: up, down, left, right
Interactive constraint: You cannot access grid dimensions or positions directly
Asked in
Minimum Path Cost in a Hidden Grid β Solution
The optimal solution uses a two-phase approach: First, systematically explore the hidden grid using DFS to map all accessible cells and their costs. Then apply Dijkstra's algorithm with a priority queue to find the true minimum cost path from start to target, properly considering the weighted edges between cells.