1 问题描述

在n*m格木板中放有一些硬币,每格的硬币数目最多为一个,在木板左上方的一个机器人需要收集尽可能多的硬币并把它们带到右下方的单元格。每一步,机器人可以从当前的位置向右移动一格或向下移动一格。当机器人遇到一个有硬币的单元格时,就会将这枚硬币收集起来。设计一个算法找出机器人能找到的最大硬币数并给出相应的路径。

2 解决方案

2.1 动态规划法


本文编码思想参考自《算法设计与分析基础》第三版,具体如下:

package com.liuzhen.chapter8;

public class RobotCoinCollection {
//输出找到最大硬币数的路径
public void getMaxPath(int[][] A){
int rowA = A.length;
int columnA = A[0].length;
//在数组A最上面一行添加一行元素0,在最左边一列添加一列元素0
int[][] changeA = new int[rowA+1][columnA+1]; //初始化,各个元素均为0
int[][] maxA = new int[rowA+1][columnA+1]; //用于计算从A[0][0]到达各元素位置收集到的最大硬币数
for(int i = 0;i < rowA;i++){
for(int j = 0;j < columnA;j++)
changeA[i+1][j+1] = A[i][j];
}
for(int i = 1;i <= rowA;i++){
for(int j = 1; j <= columnA;j++){
if(maxA[i-1][j] >= maxA[i][j-1])
maxA[i][j] = maxA[i-1][j] + changeA[i][j];
else
maxA[i][j] = maxA[i][j-1] + changeA[i][j];
}
} //输出各个元素位置收集到的最大硬币数
System.out.println("各个元素位置收集到的最大硬币数:");
for(int i = 1;i <= rowA;i++){
for(int j = 1;j <= columnA;j++)
System.out.print(maxA[i][j]+"\t");
System.out.println();
} System.out.println("从左上方到右下方收集到最大硬币数的路径(PS:其中元素为-1 表示行走路径):");
maxA[1][1] = 1; //最左上方位置
maxA[rowA][columnA] = -1; //最右下方位置
int maxI = rowA;
int maxJ = columnA;
while(maxI >= 1 && maxJ >= 1){
if(maxA[maxI][maxJ-1] >= maxA[maxI-1][maxJ]){
maxA[maxI][maxJ-1] = -1;
maxJ = maxJ - 1;
}
else{
maxA[maxI-1][maxJ] = -1;
maxI = maxI - 1;
}
} for(int i = 1;i <= rowA;i++){
for(int j = 1;j <= columnA;j++)
System.out.print(maxA[i][j]+"\t");
System.out.println();
} } public static void main(String[] args){
RobotCoinCollection test = new RobotCoinCollection();
int[][] A ={{0,0,0,0,1,0},
{0,1,0,1,0,0},
{0,0,0,1,0,1},
{0,0,1,0,0,1},
{1,0,0,0,1,0}};
test.getMaxPath(A);
}
}

运行结果:

各个元素位置收集到的最大硬币数:
0 0 0 0 1 1
0 1 1 2 2 2
0 1 1 3 3 4
0 1 2 3 3 5
1 1 2 3 4 5
从左上方到右下方收集到最大硬币数的路径(PS:其中元素为-1 表示行走路径):
-1 0 0 0 1 1
-1 -1 -1 -1 2 2
0 1 1 -1 -1 -1
0 1 2 3 3 -1
1 1 2 3 4 -1

最新文章

  1. javascript 百度地图API - demo
  2. [自学总结] Unity5.3 API 之 Audio Mixer
  3. eclipse中jre system library ,web app libraries,referenced libraries,user libraries
  4. UDP 一个封锁操作被对 WSACancelBlockingCall 的调用中断
  5. 8VC Venture Cup 2016 - Final Round (Div. 2 Edition)
  6. Uncaught SecurityError: Failed to execute &#39;replaceState&#39; on &#39;History&#39;: A history state object with
  7. Linux中/usr与/var目录详解
  8. shell配置环境变量
  9. sublimeText3安装package control和禁止弹出更新下载弹窗
  10. U3D C#脚本的生命周期
  11. tcp ip参数详解
  12. jquery ajax调用
  13. Sublime Text快捷键:
  14. T410升级笔记
  15. 阿里面试100%问到,JVM性能调优篇
  16. 实验吧 这个看起来有点简单!&amp;渗透测试工具sqlmap基础教程
  17. Swift 与 C 语言混合编程
  18. doT.js模板和pagination分页应用
  19. 雷林鹏分享:jQuery EasyUI 树形菜单 - 树形网格惰性加载节点
  20. The difference between ppp and ndis

热门文章

  1. [hdu4911]逆序对相关
  2. [hdu5195]线段树
  3. 在没有RedirectAttributes的环境中如何在重定向环境中报错错误提示信息供页面使用
  4. 20184302 2019-2020-2 《Python程序设计》实验一报告
  5. vue项目开发中遇到的问题总结
  6. 【雕爷学编程】零基础Python(01)---“投机取巧”的三条途径
  7. 剑指Offer02之替换空格
  8. MVC4.0 上传文件
  9. 如何在HTML5中使用SVG
  10. 使用脚手架 vue-cli 4.0以上版本创建vue项目