LeetCode solution summary 931. The minimum sum of the descending path

Directory link:

Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog

GitHub synchronous brushing project:

https://github.com/September26/java-algorithms

Link to the original title: Likou


describe:

Given a  n x n square  array  of integers  matrix , find and return  the minimum sum of the descending pathsmatrix  passed  .  

The descending path  can start from any element in the first row and select one element from each row. The element selected in the next row is at most one column away from the element selected in the current row (i.e., the first element directly below or diagonally to the left or right). Specifically,  (row, col) the next element of position should be  (row + 1, col - 1), (row + 1, col) or  (row + 1, col + 1) .

Example 1:

Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]
 Output: 13
 Explanation: As shown in the figure, there are two descending paths with minimum and

Example 2:

Input: matrix = [[-19,57],[-40,-5]]
 Output: -59
 Explanation: As shown in the figure, it is the smallest descending path

hint:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 100
  • -100 <= matrix[i][j] <= 100

Problem-solving ideas:

* 931. The minimum sum of the descending path

* Problem-solving ideas:

* Breadth search method.

* Construct a two-dimensional array sum of the same size to store the possible minimum value under the path. And the minimum value of the sum[y][x] position in the next line is sum[y-1][x-1], sum[y-1][x], sum[y-1][x+1] three The minimum value of the former plus itself.

* Finally, find the minimum value of the last row.

code:

class Solution931
{
public:
    int minFallingPathSum(vector<vector<int>> &matrix)
    {

        vector<vector<int>> sum(matrix.size(), vector<int>(matrix[0].size()));
        sum[0] = matrix[0];
        for (int y = 1; y < matrix.size(); y++)
        {
            for (int x = 0; x < matrix[0].size(); x++)
            {
                sum[y][x] = getMinValue(y - 1, x, sum) + matrix[y][x];
            }
        }
        int maxValue = 10000;
        for (int x = 0; x < sum[0].size(); x++)
        {
            maxValue = min(maxValue, sum[matrix.size() - 1][x]);
        }
        return maxValue;
    }

    int getMinValue(int y, int x, vector<vector<int>> &sum)
    {
        int minValue = sum[y][x];
        if (x > 0)
        {
            minValue = min(minValue, sum[y][x - 1]);
        }
        if (x < sum.size() - 1)
        {
            minValue = min(minValue, sum[y][x + 1]);
        }
        return minValue;
    }
};

Guess you like

Origin blog.csdn.net/AA5279AA/article/details/131696581