Find the minimum-cost path in a grid when movement directions must alternate according to the problem’s rules.
You are given a grid with a cost associated with entering each cell. Starting from a designated source cell, you must reach a target cell while following an alternating direction rule: consecutive moves cannot use the same movement direction category.
Compute the minimum total cost of any valid path. If no valid path exists, return an appropriate failure value as specified by the problem.
The key challenge is that the cheapest route depends not only on the current cell, but also on the direction used to arrive there, so the search state must track that extra information.
Input Format
- The first line contains the grid dimensions.
- The next lines describe the cell costs.
- The start and target positions are provided by the problem instance.
- Movement and alternation rules are defined by the statement.
Because the exact original formatting is unavailable, treat these as a generic path-cost grid input.
Output Format
- Return the minimum possible total cost among all valid alternating-direction paths.
- If no valid path exists, return the problem’s failure value.
Constraints
- Grid size is assumed to be within typical interview/LeetCode limits.
- Cell costs are non-negative.
- The alternating-direction constraint must be satisfied for every consecutive step.
- The solution should be more efficient than enumerating all paths.
Example 1
Input
grid = [[1,2,3],[4,5,6],[7,8,9]], start = (0,0), target = (2,2)
Output
20
Explanation
One valid alternating path is (0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2), with total cost 1 + 2 + 5 + 6 + 9 = 23. Another valid path may be cheaper depending on the exact alternation rule; this is an illustrative example of the format, not an official sample.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.