| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MinimumFallingPathSum2; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MinimumFallingPathSum2DynamicProgramming : IMinimumFallingPathSum2 |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n^2) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="grid"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int MinFallingPathSum(int[][] grid) |
| 2 | 24 | | { |
| 2 | 25 | | var n = grid.Length; |
| | 26 | |
|
| 2 | 27 | | if (n == 1) |
| 1 | 28 | | { |
| 1 | 29 | | return grid[0][0]; |
| | 30 | | } |
| | 31 | |
|
| 1 | 32 | | var dp = new int[n]; |
| | 33 | |
|
| 1 | 34 | | Array.Copy(grid[0], dp, n); |
| | 35 | |
|
| 6 | 36 | | for (var i = 1; i < n; i++) |
| 2 | 37 | | { |
| 2 | 38 | | var prev = new int[n]; |
| | 39 | |
|
| 2 | 40 | | Array.Copy(dp, prev, n); |
| | 41 | |
|
| 2 | 42 | | var newDp = new int[n]; |
| | 43 | |
|
| 4 | 44 | | int min1 = int.MaxValue, min2 = int.MaxValue; |
| 2 | 45 | | var idx1 = -1; |
| | 46 | |
|
| 16 | 47 | | for (var j = 0; j < n; j++) |
| 6 | 48 | | { |
| 6 | 49 | | if (prev[j] < min1) |
| 2 | 50 | | { |
| 2 | 51 | | min2 = min1; |
| 2 | 52 | | min1 = prev[j]; |
| 2 | 53 | | idx1 = j; |
| 2 | 54 | | } |
| 4 | 55 | | else if (prev[j] < min2) |
| 2 | 56 | | { |
| 2 | 57 | | min2 = prev[j]; |
| 2 | 58 | | } |
| 6 | 59 | | } |
| | 60 | |
|
| 16 | 61 | | for (var j = 0; j < n; j++) |
| 6 | 62 | | { |
| 6 | 63 | | if (j == idx1) |
| 2 | 64 | | { |
| 2 | 65 | | newDp[j] = grid[i][j] + min2; |
| 2 | 66 | | } |
| | 67 | | else |
| 4 | 68 | | { |
| 4 | 69 | | newDp[j] = grid[i][j] + min1; |
| 4 | 70 | | } |
| 6 | 71 | | } |
| | 72 | |
|
| 2 | 73 | | dp = newDp; |
| 2 | 74 | | } |
| | 75 | |
|
| 1 | 76 | | return dp.Prepend(int.MaxValue).Min(); |
| 2 | 77 | | } |
| | 78 | | } |