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.
The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and neither of them is blocked.
Each cell has a cost that you need to pay each time you move to the cell. The starting cell's cost is not applied before the robot moves.
You want to find the minimum total cost to move the robot to the target cell. However, you do not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the GridMaster object.
The GridMaster class has the following functions:
boolean canMove(char direction) Returns true if the robot can move in that direction. Otherwise, it returns false.
int move(char direction) Moves the robot in that direction and returns the cost of moving to that cell. If this move would move the robot to a blocked cell or off the grid, the move will be ignored, the robot will remain in the same position, and the function will return -1.
boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it returns false.
Note that direction in the above functions should be a character from {'U','D','L','R'}, representing the directions up, down, left, and right, respectively.
Return the minimum total cost to get the robot from its initial starting cell to the target cell. If there is no valid path between the cells, return -1.
💡 Note:In this interactive problem, the robot explores the grid using DFS to discover all reachable cells and their costs. Once exploration is complete, Dijkstra's algorithm finds the minimum cost path from start to target. The starting cell's cost is not included in the final path cost.
💡 Note:The robot explores the grid but discovers that the target cell is unreachable due to blocked cells (cost 0). The algorithm returns -1 to indicate no valid path exists.
💡 Note:The robot explores a larger grid and finds multiple possible paths. Dijkstra's algorithm efficiently determines the path with minimum total cost by considering all discovered cells and their costs.
Constraints
1 ≤ m, n ≤ 100
grid[i][j] ≥ 1 indicates the cost to move to cell (i, j)
grid[i][j] = 0 indicates that cell (i, j) is blocked
The starting and target cells are guaranteed to be different and not blocked
This interactive problem requires exploring an unknown grid while finding the minimum cost path. The optimal approach uses DFS for exploration combined with Dijkstra's algorithm for shortest path finding. Time: O(V log V + E), Space: O(V + E) where V is cells and E is edges.
Common Approaches
✓
DFS Exploration + Brute Force Path Finding
⏱️ Time: O(4^(m×n))
Space: O(m×n)
First phase uses DFS to discover all reachable cells and their costs. Second phase tries every possible path from start to target using backtracking to find the minimum cost path.
DFS Exploration + Dijkstra's Algorithm
⏱️ Time: O(V log V + E)
Space: O(V + E)
First phase uses DFS to discover all reachable cells and build a graph. Second phase applies Dijkstra's algorithm on the discovered graph to find the minimum cost path from start to target.
DFS Exploration + Brute Force Path Finding — Algorithm Steps
Step 1: Use DFS to explore and map all reachable cells
Step 2: Find target location during exploration
Step 3: Try all possible paths from start to target using backtracking
Visualization
Tap to expand
Step-by-Step Walkthrough
1
DFS Exploration
Discover all reachable cells and their costs
2
Find Target
Locate the target cell during exploration
3
Try All Paths
Use backtracking to find minimum cost path
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdbool.h>
typedef struct {
int grid[10][10];
int start[2];
int target[2];
int currentPos[2];
int rows, cols;
} GridMaster;
GridMaster* createGridMaster(const char* gridData) {
GridMaster* gm = (GridMaster*)malloc(sizeof(GridMaster));
if (strcmp(gridData, "GridMasterInstance1") == 0) {
int grid_data[3][3] = {{1,3,1},{1,0,1},{4,2,1}};
gm->rows = 3; gm->cols = 3;
gm->start[0] = 2; gm->start[1] = 0;
gm->target[0] = 2; gm->target[1] = 2;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
gm->grid[i][j] = grid_data[i][j];
}
}
} else if (strcmp(gridData, "GridMasterInstance2") == 0) {
int grid_data[3][3] = {{0,0,0},{1,1,1},{0,0,1}};
gm->rows = 3; gm->cols = 3;
gm->start[0] = 1; gm->start[1] = 0;
gm->target[0] = 1; gm->target[1] = 2;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
gm->grid[i][j] = grid_data[i][j];
}
}
} else if (strcmp(gridData, "GridMasterInstance3") == 0) {
int grid_data[3][4] = {{1,1,1,1},{2,2,2,2},{1,1,1,1}};
gm->rows = 3; gm->cols = 4;
gm->start[0] = 0; gm->start[1] = 0;
gm->target[0] = 2; gm->target[1] = 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
gm->grid[i][j] = grid_data[i][j];
}
}
} else if (strcmp(gridData, "GridMasterInstance4") == 0) {
int grid_data[4][5] = {{2,3,3,1,2},{1,4,2,3,1},{3,1,1,2,4},{2,3,2,1,1}};
gm->rows = 4; gm->cols = 5;
gm->start[0] = 0; gm->start[1] = 0;
gm->target[0] = 3; gm->target[1] = 4;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
gm->grid[i][j] = grid_data[i][j];
}
}
} else if (strcmp(gridData, "GridMasterInstance5") == 0) {
int grid_data[1][3] = {{1,1,1}};
gm->rows = 1; gm->cols = 3;
gm->start[0] = 0; gm->start[1] = 0;
gm->target[0] = 0; gm->target[1] = 2;
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 3; j++) {
gm->grid[i][j] = grid_data[i][j];
}
}
}
gm->currentPos[0] = gm->start[0];
gm->currentPos[1] = gm->start[1];
return gm;
}
bool canMove(GridMaster* gm, char direction) {
int row = gm->currentPos[0], col = gm->currentPos[1];
int newRow, newCol;
switch (direction) {
case 'U': newRow = row - 1; newCol = col; break;
case 'D': newRow = row + 1; newCol = col; break;
case 'L': newRow = row; newCol = col - 1; break;
case 'R': newRow = row; newCol = col + 1; break;
default: return false;
}
if (newRow >= 0 && newRow < gm->rows && newCol >= 0 && newCol < gm->cols) {
return gm->grid[newRow][newCol] > 0;
}
return false;
}
int move(GridMaster* gm, char direction) {
if (!canMove(gm, direction)) {
return -1;
}
int row = gm->currentPos[0], col = gm->currentPos[1];
switch (direction) {
case 'U': gm->currentPos[0] = row - 1; break;
case 'D': gm->currentPos[0] = row + 1; break;
case 'L': gm->currentPos[1] = col - 1; break;
case 'R': gm->currentPos[1] = col + 1; break;
}
return gm->grid[gm->currentPos[0]][gm->currentPos[1]];
}
bool isTarget(GridMaster* gm) {
return gm->currentPos[0] == gm->target[0] && gm->currentPos[1] == gm->target[1];
}
typedef struct {
char key[50];
int cost;
} GridCell;
typedef struct {
int cost;
int row;
int col;
} PQItem;
#define MAX_CELLS 10000
static GridCell grid[MAX_CELLS];
static int gridSize = 0;
static int targetRow = INT_MAX, targetCol = INT_MAX;
static bool targetFound = false;
int findInGrid(int row, int col) {
char key[50];
sprintf(key, "%d,%d", row, col);
for (int i = 0; i < gridSize; i++) {
if (strcmp(grid[i].key, key) == 0) {
return i;
}
}
return -1;
}
void addToGrid(int row, int col, int cost) {
char key[50];
sprintf(key, "%d,%d", row, col);
strcpy(grid[gridSize].key, key);
grid[gridSize].cost = cost;
gridSize++;
}
void dfsExplore(GridMaster* master, int row, int col) {
if (isTarget(master)) {
targetRow = row;
targetCol = col;
targetFound = true;
}
char directions[] = {'U', 'D', 'L', 'R'};
int moves[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
char opposite[] = {'D', 'U', 'R', 'L'};
for (int i = 0; i < 4; i++) {
char direction = directions[i];
if (canMove(master, direction)) {
int dr = moves[i][0], dc = moves[i][1];
int newRow = row + dr, newCol = col + dc;
if (findInGrid(newRow, newCol) == -1) {
int cost = move(master, direction);
if (cost != -1) {
addToGrid(newRow, newCol, cost);
dfsExplore(master, newRow, newCol);
move(master, opposite[i]);
}
}
}
}
}
int solution(GridMaster* master) {
gridSize = 0;
targetFound = false;
targetRow = INT_MAX;
targetCol = INT_MAX;
if (isTarget(master)) {
return 0;
}
addToGrid(0, 0, 0);
dfsExplore(master, 0, 0);
if (!targetFound) {
return -1;
}
PQItem pq[MAX_CELLS];
int pqSize = 0;
bool visited[MAX_CELLS];
memset(visited, false, sizeof(visited));
pq[pqSize++] = (PQItem){0, 0, 0};
while (pqSize > 0) {
int minIdx = 0;
for (int i = 1; i < pqSize; i++) {
if (pq[i].cost < pq[minIdx].cost) {
minIdx = i;
}
}
PQItem current = pq[minIdx];
for (int i = minIdx; i < pqSize - 1; i++) {
pq[i] = pq[i + 1];
}
pqSize--;
int currentIdx = findInGrid(current.row, current.col);
if (currentIdx == -1 || visited[currentIdx]) {
continue;
}
visited[currentIdx] = true;
if (current.row == targetRow && current.col == targetCol) {
return current.cost;
}
int moves[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < 4; i++) {
int dr = moves[i][0], dc = moves[i][1];
int newRow = current.row + dr;
int newCol = current.col + dc;
int newIdx = findInGrid(newRow, newCol);
if (newIdx != -1 && !visited[newIdx]) {
int newCost = current.cost + grid[newIdx].cost;
pq[pqSize++] = (PQItem){newCost, newRow, newCol};
}
}
}
return -1;
}
int main() {
char gridInstance[100];
scanf("%s", gridInstance);
GridMaster* master = createGridMaster(gridInstance);
int result = solution(master);
printf("%d\n", result);
free(master);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(4^(m×n))
DFS exploration takes O(m×n) but trying all paths can be exponential
n
2n
⚡ Linearithmic
Space Complexity
O(m×n)
Hash map stores all discovered cells and DFS recursion stack
n
2n
✓ Linear Space
23.4K Views
MediumFrequency
~35 minAvg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.