矩阵最短路径和

099. 矩阵最短路径和 2025.4.8

#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <list>
#include <queue>
#include <vector>

using namespace std;

void Print(const vector<vector<int>> &grid) {
  cout << "Printing grid:" << endl;
  for (const auto &row : grid) {
    for (int col : row) {
      cout << col << " ";
    }
    cout << endl;
  }
}

class Solution {
public:
  int MinPathSum(vector<vector<int>> &grid) {
    const int rows = grid.size();
    if (!rows) {
      return -1;
    }
    const int cols = grid[0].size();
    if (!cols) {
      return -1;
    }
    auto dp = vector<vector<int>>(rows, vector<int>(cols));
    dp[0][0] = grid[0][0];
    for (int row = 1; row < rows; ++row) {
      dp[row][0] = dp[row - 1][0] + grid[row][0];
    }
    for (int col = 1; col < cols; ++col) {
      dp[0][col] = dp[0][col - 1] + grid[0][col];
    }
    for (int row = 1; row < rows; ++row) {
      for (int col = 1; col < cols; ++col) {
        dp[row][col] = min(dp[row - 1][col], dp[row][col - 1]) + grid[row][col];
      }
    }
    return dp[rows - 1][cols - 1];
  }
};

int main() {
  vector<vector<int>> intervals = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
  Solution solution;
  Print(intervals);
  const int result = solution.MinPathSum(intervals);
  cout << "Result: " << result << endl;
  vector<vector<int>> grid2 = {{1, 2, 3}, {4, 5, 6}};
  Print(grid2);
  const int result2 = solution.MinPathSum(grid2);
  cout << "Result2: " << result2 << endl;
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值