当前位置:   article > 正文

动态规划(dp)之路径规划(Path Planning)_动态路径规划

动态路径规划

五步走:

1、状态表示;

2、转移方程;(核心)

3、初始化

        (1)赋值

        (2)赋值虚拟位置(虚拟表的值、映射));

4、填表顺序;

5、返回值。

 

 

 

 

 

 

 

 

 

  1. //地下城游戏
  2. int calculateMinimumHP(vector<vector<int>>& dungeon) {
  3. int m = dungeon.size();
  4. int n = dungeon[0].size();
  5. vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
  6. dp[m][n - 1] = dp[m - 1][n] = 1;
  7. for (int i = m - 1; i >= 0; i--)
  8. for (int j = n - 1; j >= 0; j--)
  9. {
  10. dp[i][j] = min(dp[i][j + 1], dp[i + 1][j]) - dungeon[i][j];
  11. dp[i][j] = max(1, dp[i][j]);
  12. }
  13. return dp[0][0];
  14. }
  15. //最小路径和
  16. int minPathSum(vector<vector<int>>& grid) {
  17. int m = grid.size();
  18. int n = grid[0].size();
  19. vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
  20. dp[0][0] = dp[0][1] = dp[1][0] = 0;
  21. for (int i = 1; i <= m; i++)
  22. for (int j = 1; j <= n; j++)
  23. dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1];
  24. return dp[m][n];
  25. }
  26. //下降路径最小和
  27. int minFallingPathSum(vector<vector<int>>& matrix) {
  28. int m = matrix.size();
  29. int n = matrix[0].size();
  30. vector<vector<int>> dp(m + 1, vector<int>(n + 2, INT_MAX));
  31. for (int i = 0; i <= n + 1; i++)
  32. dp[0][i] = 0;
  33. for (int i = 1; i <= m; i++)
  34. for (int j = 1; j <= m; j++)
  35. dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i - 1][j + 1])) + matrix[i - 1][j - 1];
  36. int ret = dp[m][1];
  37. for (int j = 1; j <= n; j++)
  38. ret = min(ret, dp[n][j]);
  39. return ret;
  40. }
  41. //礼物的最大价值
  42. int maxValue(vector<vector<int>>& grid) {
  43. int m = grid.size();
  44. int n = grid[0].size();
  45. vector<vector<int>> dp(m + 1, vector<int>(n + 1));
  46. for (int i = 1; i <= m; i++)
  47. for (int j = 1; j <= n; j++)
  48. dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]) + grid[i - 1][j - 1];
  49. return dp[m][n];
  50. }
  51. //不同路径
  52. int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
  53. int m = obstacleGrid.size(); //行
  54. int n = obstacleGrid[0].size(); //列
  55. vector<vector<int>> dp(m + 1, vector<int>(n + 1));
  56. dp[1][0] = 1;
  57. for (int i = 1; i <= m; i++)
  58. for (int j = 1; j <= n; j++)
  59. {
  60. if (obstacleGrid[i][j] == 0)
  61. dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
  62. }
  63. return dp[m][n];
  64. }
  65. //路径规划
  66. int uniquePaths(int m, int n) {
  67. vector<vector<int>> dp(m + 1, vector<int>(n + 1));
  68. dp[0][1] = 1;
  69. for (int i = 1; i <= m; i++)
  70. for (int j = 1; j <= n; j++)
  71. dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
  72. return dp[m][n];
  73. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/716695
推荐阅读
相关标签
  

闽ICP备14008679号