27 · Shortest Paths

#1368 Minimum Cost to Make at Least One Valid Path in a Grid

Hardsolve on LeetCode ↗

frequently reported atGoogle

the problem

In plain words

Each cell has a sign: 1 → right, 2 → left, 3 → down, 4 → up. From (0, 0) you follow signs for free. Changing a cell's sign costs 1 (once per cell). Return the minimum total cost so that some path reaches the bottom-right cell.

in grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]

out 3

Change three signs to step down at the ends of rows.

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

out 0

Following signs already reaches the corner.

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

out 1

  • 1 ≤ m, n ≤ 100
  • 1 ≤ grid[i][j] ≤ 4

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #2290
    2. #1091