NC59 矩阵的最小路径和

本文解析了如何使用动态规划解决从矩阵左上角到右下角的最短路径问题,通过递推方程dp[row][col] = min(dp[row-1][col], dp[row][col-1]) + matrix[row][col],并初始化边界情况,最终返回dp[rows-1][cols-1]。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

给定一个 n * m 的矩阵 a,从左上角开始每次只能向右或者向下走,最后到达右下角的位置,路径上所有的数字累加起来就是路径和,输出所有的路径中最小的路径和。

解题分析:

因为路径只能往右走和往下走,所以使用动态规划,递推方程为:
dp[row][col]=min(dp[row-1][col], dp[row][col-1])+matrix[row][col];
注意需要出示话dp的第一行和第一列,因为无法用递推公式求得。

class Solution {
public:
    /**
     * 
     * @param matrix int整型vector<vector<>> the matrix
     * @return int整型
     */
    int minPathSum(vector<vector<int> >& matrix) {
        // write code here
        int rows=matrix.size();
        int cols=matrix[0].size();
        if(rows==0 && cols==0)
            return 0;
        vector<vector<int>> dp(rows, vector<int>(cols));
        dp[0][0]=matrix[0][0];
        for(int row=1; row<rows; ++row){
            dp[row][0]=dp[row-1][0]+matrix[row][0];
        }
        for(int col=1; col<cols; ++col){
            dp[0][col]=dp[0][col-1]+matrix[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])+matrix[row][col];
            }
        }
        return dp[rows-1][cols-1];
    }
};
### MATLAB 中的地图路径规划算法示例 在 MATLAB 中实现地图路径规划通常涉及多种算法,例如 A* 算法、Dijkstra 算法以及 RRT(Rapidly-exploring Random Trees)。以下是基于这些常见方法的一个简单实例。 #### 使用 Dijkstra 算法进路径规划 Dijkstra 是一种经典的最短路径算法,在网格环境中可以有效找到两点之间的最优路径。下面是一个简单的 MATLAB 实现: ```matlab function path = dijkstra(map, start, goal) % 初始化距离矩阵前驱节点矩阵 [rows, cols] = size(map); distance = inf(rows, cols); predecessor = zeros(rows, cols); % 设置起点的距离为0 distance(start(1), start(2)) = 0; % 创建未访问集合并初始化优先队 unvisited = true(size(map)); while any(unvisited(:)) % 找到当前最小距离的节点 current = find(distance .* unvisited == min(distance(unvisited)), 1); % 如果目标已被访问,则退出循环 if isequal(current, sub2ind([rows,cols],goal(1),goal(2))) break; end % 更新邻居节点的距离 neighbors = get_neighbors(current, rows, cols, map); for i = 1:length(neighbors) neighbor = neighbors(i,:); alt_distance = distance(sub2ind([rows,cols],current(1),current(2))) + cost(map(neighbor(1), neighbor(2))); if alt_distance < distance(neighbor(1), neighbor(2)) distance(neighbor(1), neighbor(2)) = alt_distance; predecessor(neighbor(1), neighbor(2)) = sub2ind([rows,cols],current(1),current(2)); end end % 将当前节点标记为已访问 unvisited(current(1), current(2)) = false; end % 构建最终路径 path = reconstruct_path(predecessor, start, goal); end % 辅助函数:获取相邻节点 function neighbors = get_neighbors(node, rows, cols, map) r = floor((node-1)/cols)+1; c = mod(node-1, cols)+1; directions = [-1 0; 1 0; 0 -1; 0 1]; valid_neighbors = []; for d = 1:size(directions,1) nr = r + directions(d,1); nc = c + directions(d,2); if nr >=1 && nr <=rows && nc>=1 && nc<=cols && map(nr,nc)==0 valid_neighbors(end+1,:) = [nr, nc]; end end neighbors = valid_neighbors; end % 辅助函数:重建路径 function path = reconstruct_path(predecessor, start, goal) path = []; current = sub2ind(size(predecessor), goal(1), goal(2)); while ~isequal(current, []) path = [ind2sub(size(predecessor), current); path]; current = predecessor(path(1,1),path(1,2)); end end % 辅助函数:计算代价 function c = cost(value) if value == 0 c = 1; else c = Inf; end end ``` 此代码实现了基本的 Dijkstra 算法来寻找二维栅格地图中的最短路径[^1]。用户可以通过定义 `map` 来指定障碍物的位置,并通过设置起始点终点来进测试。 #### 使用 A* 算法优化路径规划 A* 算法是一种启发式搜索算法,它结合了实际成本估计剩余成本,从而更快地找到最佳路径。下面是其简化版本: ```matlab function path = a_star(map, start, goal) openList = struct('pos', {start}, 'gScore', {0}, 'fScore', {heuristic(start, goal)}); closedList = []; while ~isempty(openList) [~, idx] = min([openList.fScore]); currentNode = openList(idx).pos; if isequal(currentNode, goal) returnPath = reconstruct_aStar_path(closedList, currentNode); path = flipud(returnPath); return; end openList(idx) = []; % Remove from open list closedList{end+1} = struct('pos', currentNode, 'cameFrom', [], 'gScore', NaN, 'fScore', NaN); neighbors = get_neighbors(currentNode, size(map,1), size(map,2), map); for n = 1:numel(neighbors) tentative_gScore = closedList{end}.gScore + heuristic(currentNode, neighbors(n,:)); if contains_pos(closedList, neighbors(n,:)) continue; elseif ~contains_pos(openList, neighbors(n,:)) newEntry = struct('pos', neighbors(n,:), ... 'gScore', tentative_gScore, ... 'fScore', tentative_gScore + heuristic(neighbors(n,:), goal)); openList{end+1} = newEntry; else old_gScore = get_field_value(openList, 'gScore', neighbors(n,:)); if (tentative_gScore < old_gScore) update_open_list(openList, neighbors(n,:), tentative_gScore, goal); end end end end path = []; end function h = heuristic(a,b) h = abs(b(1)-a(1)) + abs(b(2)-a(2)); % Manhattan Distance end function p = reconstruct_aStar_path(list,pos) p = pos; for k=numel(list):-1:1 if isequal(pos,list{k}.pos) pos = list{k}.cameFrom; p = [p; pos]; end end end ``` 这段代码展示了如何利用曼哈顿距离作为启发函数完成更高效的路径查找过程[^2]。 #### 结合 Robotics System Toolbox 的功能 如果拥有 MATLAB 的 **Robotics System Toolbox**,可以直接调用内置工具箱的功能快速构建复杂环境下的路径规划解决方案。例如使用 `mobileRobotPRM` 者 `navGraph` 对象创建导航图谱,并应用各种高级策略解决动态避障等问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值