oneby7

Advanced Graphs 0-1 BFS

597. Minimum Cost to Make at Least One Valid Path in a Grid

Hard

You are given an m × n grid, grid. Every cell holds a sign that points to one of its four neighbours:

  • 1 points right, to grid[i][j + 1]
  • 2 points left, to grid[i][j - 1]
  • 3 points down, to grid[i + 1][j]
  • 4 points up, to grid[i - 1][j]

A sign on the edge of the grid may point outside it.

You start in the top-left cell and walk by following the signs: from each cell you move to the cell its sign points to. A walk is valid if it reaches the bottom-right cell. It does not have to be the shortest walk.

You may change the sign of any cell to point in another direction. Each change costs 1, and each cell's sign can be changed at most once. Return the smallest total cost that makes the walk from the top-left cell valid.

Example 1

113232241142

Input: grid = [[1, 1, 3, 2], [3, 2, 2, 4], [1, 1, 4, 2]]

Output: 1

Explanation: The signs lead right, right, down, left, left, down, right and right. Then the third cell of the bottom row points up, and the walk goes round in a loop. Changing that one sign to 1 sends the walk into the bottom-right cell.

Example 2

222

Input: grid = [[2, 2, 2]]

Output: 2

Explanation: Every sign points left, and the first one points out of the grid. The first two signs must both change to 1. The last cell's own sign does not matter.

Example 3

313143422

Input: grid = [[3, 1, 3], [1, 4, 3], [4, 2, 2]]

Output: 0

Explanation: The signs already lead down, right, up, right, down and down, which ends in the bottom-right cell. Nothing needs to change.

Check your understanding

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

grid = [[1, 1, 1, 3], [3, 2, 2, 2], [1, 1, 1, 1]]

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • 1 ≤ grid[i][j] ≤ 4

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.