← All problems

2684. Maximum Number of Moves in a Grid

MediumOpen on LeetCodeProblem statement

Problem Statement

2684. Maximum Number of Moves in a Grid

Medium


You are given a 0-indexed m x n matrix grid consisting of positive integers.

You can start at any cell in the first column of the matrix, and traverse the grid in the following way:

Return the maximum number of moves that you can perform.

 

Example 1:

Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]]
Output: 3
Explanation: We can start at the cell (0, 0) and make the following moves:
- (0, 0) -> (0, 1).
- (0, 1) -> (1, 2).
- (1, 2) -> (2, 3).
It can be shown that it is the maximum number of moves that can be made.

Example 2:


Input: grid = [[3,2,4],[2,1,9],[1,1,7]]
Output: 0
Explanation: Starting from any cell in the first column we cannot perform any moves.

 

Constraints:

Java

Source file
class Solution {
    int m, n;
    int[][] memo;

    public int maxMoves(int[][] grid) {
        this.m = grid.length;
        this.n = grid[0].length;
        memo = new int[m][n];
        int maxPathLen = 0;
        for (int i = 0; i < m; i++)
            maxPathLen = Math.max(maxPathLen, backtrack(grid, i, 0, -1, 0));
        return maxPathLen;
    }

    private int backtrack(int[][] grid, int r, int c, int prevVal, int pathLen) {
        if (r < 0 || c < 0 || r >= m || c >= n || prevVal >= grid[r][c])
            return pathLen - 1;
        if (memo[r][c] != 0)
            return memo[r][c];
        return memo[r][c] = Math.max(
                backtrack(grid, r - 1, c + 1, grid[r][c], pathLen + 1),
                Math.max(backtrack(grid, r, c + 1, grid[r][c], pathLen + 1),
                        backtrack(grid, r + 1, c + 1, grid[r][c], pathLen + 1)));
    }

}