1368. Minimum Cost to Make at Least One Valid Path in a Grid - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

You are given an m x n grid where each cell contains an integer from 1 to 4 that represents a direction:

  • 1 means move right,
  • 2 means move left,
  • 3 means move down, and
  • 4 means move up.

Starting at the top-left cell (0, 0), your goal is to reach the bottom-right cell (m-1, n-1). You can follow the direction indicated in a cell at no cost. However, you may change the direction of a cell at a cost of 1. The task is to determine the minimum cost required to modify some directions so that there is at least one valid path from (0, 0) to (m-1, n-1).

Example Inputs, Outputs, and Explanations

Example 1

Input:

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

Output:

0

Explanation:
Following the arrows as given, a valid path exists:

  • Start at (0, 0) with value 1 (right) → move to (0, 1).
  • (0, 1) with value 1 (right) → move to (0, 2).
  • (0, 2) with value 3 (down) → move to (1, 2).
  • (1, 2) with value 2 (left) → move to (1, 1).
  • (1, 1) with value 2 (left) → move to (1, 0).
  • (1, 0) with value 3 (down) → move to (2, 0).
  • (2, 0) with value 1 (right) → move to (2, 1).
  • (2, 1) with value 1 (right) → move to (2, 2), the destination.

No changes are needed, so the minimum cost is 0.

Example 2

Input:

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

Output:

1

Explanation:

  • At (0, 0), the arrow is 1 (right) → move to (0, 1).
  • At (0, 1), the arrow is 2 (left) which sends you back to (0, 0), forming a loop.

To create a valid path, change the arrow at (0, 1) from 2 to 3 (down) so that:

  • (0, 0) → (0, 1) → (1, 1) reaches the destination.

The minimum cost incurred is 1.

Example 3

Input:

grid = [
  [2, 2],
  [2, 2]
]

Output:

2

Explanation:
All cells initially point left (2), which is not useful at (0, 0) since left would go out-of-bound. One possible solution is:

  • Change (0, 0) from 2 to 1 (right) so you can move to (0, 1) at a cost of 1.
  • At (0, 1), change from 2 to 3 (down) so that you move to (1, 1) at an additional cost of 1.

The total minimum cost is 2.

Constraints

  • The grid dimensions m and n can be relatively large.
  • Each cell’s value is an integer from 1 to 4.
  • The grid may contain cycles or lead out-of-bound if directions are not modified.
  • A valid path from the start to the destination is always possible after making some changes.

Hints for the Approach

  1. Graph Representation:
    Treat each cell in the grid as a node. Moving from one cell to its neighbor based on the current direction costs 0, while deviating (changing the arrow) costs 1.

  2. 0-1 BFS:
    Since the edge weights are only 0 and 1, the 0-1 BFS technique is ideal. Use a deque (double-ended queue) to ensure that zero-cost moves are processed before costlier moves.

  3. Cost Tracking:
    Use a cost (or distance) matrix to keep track of the minimum cost needed to reach each cell.

Approach 1: Brute Force / DFS (Not Practical)

Explanation

A brute force method would explore all possible paths from (0, 0) to (m-1, n-1) while keeping track of the cost incurred. This approach involves:

  • Trying every possible combination of moves.
  • Backtracking when a dead-end is reached.

Drawbacks

  • Time complexity is exponential.
  • Not feasible for large grids.

Approach 2: Optimal Approach Using 0-1 BFS

Explanation

This approach treats the grid as a graph with edge weights 0 (following the current arrow) or 1 (changing the arrow). It uses a deque to process cells based on their current cost:

  • Initialization:
    Create a cost matrix initialized with infinity (or a very high value) for each cell and set the starting cell (0, 0) cost to 0.

  • 0-1 BFS Process:

    • Use a deque and add the starting cell.
    • For each cell, consider the four possible moves (right, left, down, up).
    • Determine the cost to move to a neighbor:
      • If the move matches the arrow in the current cell, the cost is 0.
      • Otherwise, the cost is 1.
    • If moving to a neighbor results in a lower cost than previously recorded, update the cost and add the neighbor to the deque:
      • Add to the front if cost is 0.
      • Add to the back if cost is 1.

Step-by-Step Walkthrough

  1. Set Up:
    Create a 2D cost matrix of size m x n filled with infinity, except cost[0][0] = 0. Initialize a deque with the starting position (0, 0).

  2. Process Each Cell:
    While the deque is not empty, remove a cell from the front. For each possible direction:

    • Compute the neighbor’s coordinates.
    • Check if the neighbor is within bounds.
    • Calculate the new cost (current cost plus 0 if moving in the indicated direction, or plus 1 if not).
    • If this new cost is less than the recorded cost at the neighbor, update the neighbor’s cost and add it to the deque accordingly.
  3. Result:
    The value in cost[m-1][n-1] represents the minimum cost to reach the destination.

Code Implementation

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Complexity Analysis

  • Time Complexity:
    Every cell is processed at most once, and each cell checks 4 directions. Thus, the time complexity is O(m * n).

  • Space Complexity:
    The cost matrix and the deque each require O(m * n) space.

Common Mistakes and Edge Cases

  • Boundary Checks:
    Always verify that the neighbor cell coordinates are within the grid bounds.

  • Direction Comparison:
    Ensure that when comparing the current cell’s arrow with a direction, you account for the fact that grid values range from 1 to 4 while your direction array indices are 0-based.

  • Infinite Loops:
    Prevent reprocessing cells by only updating and adding a cell to the deque when a lower cost is found.

  • Edge Case – Single Cell Grid:
    When the grid contains only one cell, the answer is 0 since you are already at the destination.

TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;