Skip to content

2684. Maximum Number of Moves in a Grid 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int maxMoves(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    int ans = 0;
    // dp[i][j] := the maximum number of moves you can perform from (i, j)
    vector<vector<int>> dp(m, vector<int>(n));

    for (int j = n - 2; j >= 0; --j)
      for (int i = 0; i < m; ++i) {
        if (grid[i][j + 1] > grid[i][j])
          dp[i][j] = 1 + dp[i][j + 1];
        if (i > 0 && grid[i - 1][j + 1] > grid[i][j])
          dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1]);
        if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j])
          dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1]);
      }

    for (int i = 0; i < m; ++i)
      ans = max(ans, dp[i][0]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int maxMoves(int[][] grid) {
    final int m = grid.length;
    final int n = grid[0].length;
    int ans = 0;
    // dp[i][j] := the maximum number of moves you can perform from (i, j)
    int[][] dp = new int[m][n];

    for (int j = n - 2; j >= 0; --j)
      for (int i = 0; i < m; ++i) {
        if (grid[i][j + 1] > grid[i][j])
          dp[i][j] = 1 + dp[i][j + 1];
        if (i > 0 && grid[i - 1][j + 1] > grid[i][j])
          dp[i][j] = Math.max(dp[i][j], 1 + dp[i - 1][j + 1]);
        if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j])
          dp[i][j] = Math.max(dp[i][j], 1 + dp[i + 1][j + 1]);
      }

    for (int i = 0; i < m; ++i)
      ans = Math.max(ans, dp[i][0]);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def maxMoves(self, grid: list[list[int]]) -> int:
    m = len(grid)
    n = len(grid[0])
    # dp[i][j] := the maximum number of moves you can perform from (i, j)
    dp = [[0] * n for _ in range(m)]

    for j in range(n - 2, -1, -1):
      for i in range(m):
        if grid[i][j + 1] > grid[i][j]:
          dp[i][j] = 1 + dp[i][j + 1]
        if i > 0 and grid[i - 1][j + 1] > grid[i][j]:
          dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1])
        if i + 1 < m and grid[i + 1][j + 1] > grid[i][j]:
          dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1])

    return max(dp[i][0] for i in range(m))