LeetCode/java/maximum-number-of-moves-in-a-grid.java
2024-01-03 19:04:35 +01:00

27 lines
757 B
Java

class Solution {
public int maxMoves(int[][] grid) {
int[][] dp = new int[grid.length][grid[0].length];
for (int x = grid[0].length - 2; x >= 0; --x) {
for (int y = 0; y < dp.length; ++y) {
// check neighbours for moves
for (int dy = -1; dy <= 1; ++dy) {
int ny = y + dy;
if (ny < 0 || ny >= dp.length || grid[y][x] >= grid[ny][x + 1]) {
continue;
}
dp[y][x] = Math.max(dp[y][x], 1 + dp[ny][x + 1]);
}
}
}
int m = 0;
for (int y = 0; y < grid.length; ++y) {
m = Math.max(m, dp[y][0]);
}
return m;
}
}