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 26
| class Solution { public int minFallingPathSum(int[][] grid) { int n = grid.length; int[][] f = new int[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { f[i][j] = Integer.MAX_VALUE; } } System.arraycopy(grid[0], 0, f[0], 0, n); for (int i = 1; i < n; ++i) { for (int j = 0; j < n; ++j) { for (int k = 0; k < n; ++k) { if (j != k) { f[i][j] = Math.min(f[i][j], f[i - 1][k] + grid[i][j]); } } } } int ans = Integer.MAX_VALUE; for (int x : f[n - 1]) { ans = Math.min(ans, x); } return ans; } }
|