
Problem
Solution
Submissions
Shortest Path in a Grid
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the shortest path from the top-left corner to the bottom-right corner of a grid, where you can eliminate at most k obstacles. The grid contains 0s (empty cells) and 1s (obstacles). You can move in 4 directions (up, down, left, right) and can eliminate obstacles by walking through them, but you have a limited number of eliminations.
Example 1
- Input: grid = [[0,0,0],[1,1,0],[0,0,0]], k = 1
- Output: 6
- Explanation:
- Start at (0,0) and need to reach (2,2).
- Path: (0,0) → (0,1) → (0,2) → (1,2) → (2,2) = 4 moves.
- Alternative path eliminating obstacle: (0,0) → (1,0) → (2,0) → (2,1) → (2,2) = 4 moves.
- The shortest path length is 6 steps.
- Start at (0,0) and need to reach (2,2).
Example 2
- Input: grid = [[0,1,1,0,0,0],[0,0,0,1,1,0],[0,1,0,0,1,0],[1,0,0,1,1,0],[1,1,0,0,0,0]], k = 1
- Output: 10
- Explanation:
- The grid is 5x6 and we can eliminate at most 1 obstacle.
- Find the optimal path that uses at most 1 elimination.
- The shortest path requires 10 steps.
- The grid is 5x6 and we can eliminate at most 1 obstacle.
Constraints
- 1 ≤ grid.length, grid[0].length ≤ 40
- 1 ≤ k ≤ grid.length * grid[0].length
- grid[i][j] is 0 (empty) or 1 (obstacle)
- Time Complexity: O(m * n * k)
- Space Complexity: O(m * n * k)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use BFS (Breadth-First Search) to find the shortest path
- Track the state as (row, col, remaining_eliminations)
- Use a 3D visited array to avoid revisiting the same state
- For each cell, try moving in all 4 directions
- If the next cell is an obstacle, use one elimination (if available)
- Return the number of steps when reaching the destination