oneby7

Advanced Graphs 0-1 BFS

596. Minimum Obstacle Removal to Reach Corner

Hard

You are given a grid of integers, grid, with m rows and n columns. A cell that holds 0 is empty, and a cell that holds 1 has an obstacle in it. You can remove any obstacle, and its cell then becomes empty.

You start in the top-left cell, (0, 0), and want to reach the bottom-right cell, (m - 1, n - 1). Each step moves to the cell directly above, below, left or right, and it may only land on an empty cell.

Return the smallest number of obstacles you must remove so that a path from the top-left cell to the bottom-right cell exists.

Example 1

01000010100001111110

Input: grid = [[0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 1], [1, 1, 1, 1, 0]]

Output: 1

Explanation: Removing the obstacle at (2, 4) is enough. The path goes down the left column, right along row 2 to (2, 2), up to the top row, right to (0, 4), and then down the right column through (2, 4).

Example 2

011010

Input: grid = [[0, 1, 1, 0, 1, 0]]

Output: 3

Explanation: The grid is a single row, so there is only one path, and it passes all three obstacles.

Example 3

011111111110

Input: grid = [[0, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 0]]

Output: 4

Explanation: Every cell but the two corners has an obstacle. Every path passes at least 4 cells between the corners, and each of them has to be cleared.

Check your understanding

Work out the answer for this input before you write any code.

grid = [[0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0]]

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m, n ≤ 105
  • 2 ≤ m · n ≤ 105
  • grid[i][j] is 0 or 1.
  • grid[0][0] == grid[m - 1][n - 1] == 0

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.