Skip to main content
LeetCode 1368, Medium. Topics: Array, Breadth-First Search, Graph, Heap (Priority Queue), Matrix, Shortest Path. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 24 parametrized pytest cases, and a playground notebook:

Problem

Given an <code>m x n</code> grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of <code>grid[i][j]</code> can be: <ul> <li><code>1</code> which means go to the cell to the right. (i.e go from <code>grid[i][j]</code> to <code>grid[i][j + 1]</code>)</li> <li><code>2</code> which means go to the cell to the left. (i.e go from <code>grid[i][j]</code> to <code>grid[i][j - 1]</code>)</li> <li><code>3</code> which means go to the lower cell. (i.e go from <code>grid[i][j]</code> to <code>grid[i + 1][j]</code>)</li> <li><code>4</code> which means go to the upper cell. (i.e go from <code>grid[i][j]</code> to <code>grid[i - 1][j]</code>)</li> </ul> Notice that there could be some signs on the cells of the grid that point outside the grid. You will initially start at the upper left cell <code>(0, 0)</code>. A valid path in the grid is a path that starts from the upper left cell <code>(0, 0)</code> and ends at the bottom-right cell <code>(m - 1, n - 1)</code> following the signs on the grid. The valid path does not have to be the shortest. You can modify the sign on a cell with <strong>cost = 1</strong>. You can modify the sign on a cell <strong>one time only</strong>. Return the <em>minimum cost to make the grid have at least one <strong>valid path</strong></em>.

Examples

Example 1
Example 2
Example 3

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
  • 1 <= grid[i][j] <= 4

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026