You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY).
The cost of going from a position (x1, y1) to any other position in the space (x2, y2) is |x2 - x1| + |y2 - y1| (Manhattan distance).
There are also some special roads. You are given a 2D array specialRoads where specialRoads[i] = [x1i, y1i, x2i, y2i, costi] indicates that the ith special road goes in one direction from (x1i, y1i) to (x2i, y2i) with a cost equal to costi. You can use each special road any number of times.
Return the minimum cost required to go from (startX, startY) to (targetX, targetY).
💡 Note:The optimal path: (1,1) → (1,2) [cost=1] → (3,3) [special road cost=2] → (4,1) [cost=3]. Total: 1+2+3=6. Direct path: |4-1|+|1-1|=3. Another path via second special road gives cost 5, which is optimal.
Minimum Cost of a Path With Special Roads — Solution
The key insight is to model this as a shortest path problem in a graph where nodes are important points (start, target, special road endpoints) and edges represent movement costs. The optimal approach uses Dijkstra's algorithm to find the minimum cost path. Time: O((V + E) log V), Space: O(V + E) where V is the number of unique points.
Common Approaches
✓
Brute Force with DFS
⏱️ Time: O(2^n)
Space: O(n)
For each position, try going directly to target or using each available special road, then recursively solve from the new position. Use memoization to avoid recomputing same states.
Dijkstra's Algorithm with Priority Queue
⏱️ Time: O((V + E) log V)
Space: O(V + E)
Build a graph where nodes are start point, target point, and all special road endpoints. Use Dijkstra's algorithm with a priority queue to find the shortest path from start to target.
Brute Force with DFS — Algorithm Steps
Start from initial position
For each special road, calculate cost to reach it + road cost + recursive cost
Also consider direct path to target
Return minimum of all options
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Start Position
Begin at start point, consider all options
2
Explore Routes
Try direct path and each special road recursively
3
Find Minimum
Return minimum cost among all explored paths
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MAX_POSITIONS 100
#define MAX_SPECIAL_ROADS 200
int abs_val(int x) {
return x < 0 ? -x : x;
}
int manhattan(int x1, int y1, int x2, int y2) {
return abs_val(x2 - x1) + abs_val(y2 - y1);
}
int min(int a, int b) {
return a < b ? a : b;
}
typedef struct {
int x, y;
} Position;
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
void parseSpecialRoads(const char* str, int specialRoads[][5], int* roadCount) {
*roadCount = 0;
if (strcmp(str, "[]") == 0) return;
const char* p = str + 1; // Skip first '['
while (*p && *p != ']') {
if (*p == '[') {
p++;
for (int i = 0; i < 5; i++) {
while (*p == ' ' || *p == ',') p++;
specialRoads[*roadCount][i] = (int)strtol(p, (char**)&p, 10);
}
(*roadCount)++;
while (*p && *p != ']') p++;
if (*p == ']') p++;
} else {
p++;
}
}
}
int findPositionIndex(Position positions[], int posCount, int x, int y) {
for (int i = 0; i < posCount; i++) {
if (positions[i].x == x && positions[i].y == y) {
return i;
}
}
return -1;
}
int solution(int* start, int* target, int specialRoads[][5], int specialRoadsSize) {
// Collect all relevant positions
Position positions[MAX_POSITIONS];
int posCount = 0;
// Add start and target
positions[posCount++] = (Position){start[0], start[1]};
int targetIndex = -1;
if (start[0] != target[0] || start[1] != target[1]) {
positions[posCount] = (Position){target[0], target[1]};
targetIndex = posCount;
posCount++;
} else {
targetIndex = 0;
}
// Add special road endpoints
for (int i = 0; i < specialRoadsSize; i++) {
int x1 = specialRoads[i][0], y1 = specialRoads[i][1];
int x2 = specialRoads[i][2], y2 = specialRoads[i][3];
if (findPositionIndex(positions, posCount, x1, y1) == -1) {
positions[posCount++] = (Position){x1, y1};
}
if (findPositionIndex(positions, posCount, x2, y2) == -1) {
positions[posCount++] = (Position){x2, y2};
}
}
// Dijkstra's algorithm
int dist[MAX_POSITIONS];
int visited[MAX_POSITIONS];
for (int i = 0; i < posCount; i++) {
dist[i] = INT_MAX;
visited[i] = 0;
}
int startIndex = findPositionIndex(positions, posCount, start[0], start[1]);
dist[startIndex] = 0;
for (int processed = 0; processed < posCount; processed++) {
int currentIndex = -1;
int minDist = INT_MAX;
// Find unvisited node with minimum distance
for (int i = 0; i < posCount; i++) {
if (!visited[i] && dist[i] < minDist) {
minDist = dist[i];
currentIndex = i;
}
}
if (currentIndex == -1 || minDist == INT_MAX) break;
visited[currentIndex] = 1;
if (currentIndex == targetIndex) {
return dist[currentIndex];
}
// Direct movement to all other positions
for (int i = 0; i < posCount; i++) {
if (!visited[i]) {
int newDist = dist[currentIndex] + manhattan(
positions[currentIndex].x, positions[currentIndex].y,
positions[i].x, positions[i].y
);
if (newDist < dist[i]) {
dist[i] = newDist;
}
}
}
// Try special roads from current position
for (int i = 0; i < specialRoadsSize; i++) {
int x1 = specialRoads[i][0], y1 = specialRoads[i][1];
int x2 = specialRoads[i][2], y2 = specialRoads[i][3], roadCost = specialRoads[i][4];
if (positions[currentIndex].x == x1 && positions[currentIndex].y == y1) {
int nextIndex = findPositionIndex(positions, posCount, x2, y2);
if (nextIndex != -1 && !visited[nextIndex]) {
int newDist = dist[currentIndex] + roadCost;
if (newDist < dist[nextIndex]) {
dist[nextIndex] = newDist;
}
}
}
}
}
return dist[targetIndex];
}
int main() {
char line[1000];
int start[2], target[2];
int specialRoads[MAX_SPECIAL_ROADS][5];
int specialRoadsSize;
// Read start
fgets(line, sizeof(line), stdin);
int startSize;
parseArray(line, start, &startSize);
// Read target
fgets(line, sizeof(line), stdin);
int targetSize;
parseArray(line, target, &targetSize);
// Read special roads
fgets(line, sizeof(line), stdin);
parseSpecialRoads(line, specialRoads, &specialRoadsSize);
int result = solution(start, target, specialRoads, specialRoadsSize);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(2^n)
Each special road can be used or not used, leading to exponential combinations
n
2n
⚠ Quadratic Growth
Space Complexity
O(n)
Recursion stack depth and memoization map
n
2n
⚡ Linearithmic Space
8.5K Views
MediumFrequency
~35 minAvg. Time
180 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.