Advanced Graphs 0-1 BFS
597. Minimum Cost to Make at Least One Valid Path in a Grid
You are given an m × n grid, grid. Every cell holds a sign that points to one of its four neighbours:
1points right, togrid[i][j + 1]2points left, togrid[i][j - 1]3points down, togrid[i + 1][j]4points up, togrid[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
Input: grid = [[1, 1, 3, 2], [3, 2, 2, 4], [1, 1, 4, 2]]
1Explanation: 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
Input: grid = [[2, 2, 2]]
2Explanation: 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
Input: grid = [[3, 1, 3], [1, 4, 3], [4, 2, 2]]
0Explanation: 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.
Constraints
m == grid.length,n == grid[i].length1 ≤ m, n ≤ 1051 ≤ m · n ≤ 1051 ≤ grid[i][j] ≤ 4
Clarifying questions
What you would ask an interviewer before writing any code.