Tap here to switch tabs
Problem
Submissions

Problem: Minimum Number of Visited Cells in a Grid

Try to solve the Minimum Number of Visited Cells in a Grid problem.

Statement

You are given a 00 indexed m×nm \times n integer matrix grid. Your starting position is at the cell (0,0)(0, 0).

When you are located at cell (i,j)(i, j), you can move to any of the following cells:

  • Cell (i,k)(i, k) such that j<k≤min⁡(j+‘grid‘[i][j],n−1)j < k \leq \min(j + {`grid`}[i][j], n - 1) (moving to the right in the same row).

  • Cell (k,j)(k, j) such that i<k≤min⁡(i+‘grid‘[i][j],m−1)i < k \leq \min(i + {`grid`}[i][j], m - 1) (moving downward in the same column).

Return the minimum number of cells you need to visit to reach the cell (m−1,n−1)(m - 1, n - 1). If the cell (m−1,n−1)(m - 1, n - 1) cannot be reached, return −1-1.

Constraints:

  • m ==== grid.length

  • n ==== grid[i].length

  • 1≤1 \leq m, n ≤105\leq 10^5

  • 1≤1 \leq m $ imes$ n ≤105\leq 10^5

  • 0≤0 \leq grid[i][j] << m ×\times n

  • grid[m - 1][n - 1] ==0== 0

⋮
Tap here to switch tabs
Problem
Submissions

Problem: Minimum Number of Visited Cells in a Grid

Try to solve the Minimum Number of Visited Cells in a Grid problem.

Statement

You are given a 00 indexed m×nm \times n integer matrix grid. Your starting position is at the cell (0,0)(0, 0).

When you are located at cell (i,j)(i, j), you can move to any of the following cells:

  • Cell (i,k)(i, k) such that j<k≤min⁡(j+‘grid‘[i][j],n−1)j < k \leq \min(j + {`grid`}[i][j], n - 1) (moving to the right in the same row).

  • Cell (k,j)(k, j) such that i<k≤min⁡(i+‘grid‘[i][j],m−1)i < k \leq \min(i + {`grid`}[i][j], m - 1) (moving downward in the same column).

Return the minimum number of cells you need to visit to reach the cell (m−1,n−1)(m - 1, n - 1). If the cell (m−1,n−1)(m - 1, n - 1) cannot be reached, return −1-1.

Constraints:

  • m ==== grid.length

  • n ==== grid[i].length

  • 1≤1 \leq m, n ≤105\leq 10^5

  • 1≤1 \leq m $ imes$ n ≤105\leq 10^5

  • 0≤0 \leq grid[i][j] << m ×\times n

  • grid[m - 1][n - 1] ==0== 0