Trains the technique from
LeetCode 1368Minimum Cost to Make at Least One Valid Path in a GridThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A sorting floor is an m x n block of cells. Every cell carries one fixed arrow, and a tote sitting on a cell is pushed to the neighbouring cell that arrow points at. grid[r][c] gives the arrow code of the cell in row r, column c:
1 points right, to (r, c + 1);2 points left, to (r, c - 1);3 points down, to (r + 1, c);4 points up, to (r - 1, c).A tote is placed on (0, 0) and must end up on (m - 1, n - 1). It only ever moves the way the arrow under it points, and it may never be pushed off the edge of the floor.
Before releasing the tote you may rewire cells. Rewiring one cell sets its arrow to any of the four directions and costs 1, and no cell may be rewired more than once. Return the smallest total cost that leaves the tote able to travel from (0, 0) to (m - 1, n - 1). A tote already standing on (m - 1, n - 1) needs no moves and no rewiring.
Example 1
Rewire the cell at row 2, column 0 to point right. The tote then runs right along row 0, down into row 1, left along row 1, down into row 2, and from there right along row 2, down, left along row 3, down and right along row 4 onto (4, 4). One rewire is paid for.
Example 2
The floor is one column wide, so every arrow points off the edge. Rewiring row 0 and row 1 to point down carries the tote from (0, 0) to (2, 0) for a cost of 2.
Example 3
The arrow on (0, 0) pushes the tote down to (1, 0), and the arrow there pushes it right onto (1, 1), so no cell needs rewiring.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def min_rewiring_cost(grid: list[list[int]]) -> int:public int minRewiringCost(int[][] grid)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.