-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution931.cs
46 lines (40 loc) · 1.13 KB
/
Solution931.cs
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution931
{
/// <summary>
/// 931. Minimum Falling Path Sum - Medium
/// <a href="https://leetcode.com/problems/minimum-falling-path-sum">See the problem</a>
/// </summary>
public int MinFallingPathSum(int[][] matrix)
{
int n = matrix.Length;
int[,] dp = new int[n, n];
for (int i = 0; i < n; i++)
{
dp[0, i] = matrix[0][i];
}
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n; j++)
{
dp[i, j] = matrix[i][j] + dp[i - 1, j];
if (j > 0)
{
dp[i, j] = Math.Min(dp[i, j], matrix[i][j] + dp[i - 1, j - 1]);
}
if (j < n - 1)
{
dp[i, j] = Math.Min(dp[i, j], matrix[i][j] + dp[i - 1, j + 1]);
}
}
}
int result = int.MaxValue;
for (int i = 0; i < n; i++)
{
result = Math.Min(result, dp[n - 1, i]);
}
return result;
}
}