NC59 矩阵的最小路径和

该博客介绍了一个算法问题,即在给定的二维矩阵中,从左上角出发,每次只能向右或向下移动,目标是找到所有可能路径中最小的路径和。示例给出了一个具体的矩阵和对应的最小路径和12。解决方案使用动态规划实现,通过填充一个dp矩阵来计算每个位置的最小路径和。

NC59 矩阵的最小路径和

描述
给定一个 n * m 的矩阵 a,从左上角开始每次只能向右或者向下走,最后到达右下角的位置,路径上所有的数字累加起来就是路径和,输出所有的路径中最小的路径和。
示例1
输入:
[[1,3,5,9],[8,1,3,4],[5,0,6,1],[8,8,4,0]]
复制
返回值:
12

import java.util.*;


public class Solution {
    /**
     * 
     * @param matrix int整型二维数组 the matrix
     * @return int整型
     */
    public int minPathSum (int[][] matrix) {
        // write code here
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return 0 ;
        }
        int m = matrix.length ;
        int n = matrix[0].length ;
        int[][] dp = new int[m][n] ;
        dp[0][0] = matrix[0][0] ;
        for(int i = 1 ; i < m ; i++){
            dp[i][0] = dp[i-1][0] + matrix[i][0] ;
        }
        for(int j = 1 ; j < n ; j++){
            dp[0][j] = dp[0][j-1] + matrix[0][j] ;
        }
        for(int i = 1 ;  i < m ; i++){
            for(int j = 1 ; j < n ; j++){
                dp[i][j] = Math.min(dp[i-1][j] , dp[i][j-1]) + matrix[i][j] ;
            }
        }
        return dp[m-1][n-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` 对象创建导航图谱,并应用各种高级策略解决动态避障等问题。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值