Tutorialspoint
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.
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.
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)
ArraysAlgorithmseBayTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize a BFS queue with the starting state (0, 0, k eliminations, 0 steps)
 Step 2: Create a 3D visited array to track states [row][col][remaining_eliminations]
 Step 3: For each state, try moving in all 4 directions (up, down, left, right)
 Step 4: If the next cell is an obstacle, check if we have eliminations left and use one
 Step 5: If we reach the destination, return the current number of steps
 Step 6: Mark visited states to avoid cycles and continue BFS until queue is empty
 Step 7: Return -1 if no valid path is found within the elimination limit

Submitted Code :