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!

Input & Output

example_1.py β€” Basic Grid Navigation
$ Input: grid = [[3,1,1,2],[1,2,3,1],[4,2,1,0],[2,3,1,1]] start = (0,0), target = (3,3)
β€Ί Output: 6
πŸ’‘ 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.
example_2.py β€” Blocked Cells
$ Input: grid = [[2,1,0,3],[1,0,2,1],[4,1,2,1]] start = (0,0), target = (2,3)
β€Ί Output: 8
πŸ’‘ 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.
example_3.py β€” No Valid Path
$ Input: grid = [[1,0,0],[0,2,0],[0,0,1]] start = (0,0), target = (2,2)
β€Ί Output: -1
πŸ’‘ 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

n
2n
βœ“ Linear Space

Constraints

  • 1 ≀ m, n ≀ 200 (grid dimensions)
  • 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
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen