利用动态规划求迷宫的最优值问题

【问题】7月5号的那道题的动态规划解法和如下这道的动态规划解法大体一致

 

2

从【0,0】出发走到底线处即停止,矩阵中每个元素的值为该处可以获得的价值,问到达底线时能获得的最大值。

【动态规划】

 规划一个二维矩阵和4*4,然后按照一横一竖的顺序一层一层求出反写的L形的值,每个元素的值为其上方和左侧元素的最大值加上该处获得的值之和。最下一层的值只能通过其上的位置达到。

【算法程序】

#include <iostream> #include <vector> #define MaxSize 4 using namespace std; //Original Maze int Maze[MaxSize][MaxSize]= { {0,2,3,20}, {2,0,6,90}, {1,0,4,-1}, {4,13,12,90} }; //From Original Point To The Best Point of Bottom Line int PathCount=0; /// <summary> /// Print the (*Maze)[MaxSize] /// </summary> /// <param name="maze"></param> /// <returns></returns> template<typename T> void ShowMaze(T (*maze)[MaxSize]) { for(int i=0;i<MaxSize;++i) { cout<<" "; for(int j=0;j<MaxSize;++j) cout<<maze[i][j]<<" "; cout<<endl; } return; } /// <summary> /// Get The _mazeA from _maze[Core Alogrithm-解决问题的核心算法动态规划] /// </summary> /// <param name="_maze">Original Maze</param> /// <param name="_mazeA">Result Maze</param> /// <returns></returns> void MakePlan_AsMaze(int (*_maze)[MaxSize], int (*_mazeA)[MaxSize]) { _mazeA[0][0]=_maze[0][0];/*Start Point*/ for(int i=1;i<MaxSize;++i)/*lineNo-ColNo==i And ColNo-lineNo==i*/ { for(int k=0;k<i;++k) { if(_maze[i][k]>=0)/*Row Direction Element*/ { if(k>0) { if(i<MaxSize-1)_mazeA[i][k]=(_mazeA[i][k-1]>_mazeA[i-1][k])?(_mazeA[i][k-1]+_maze[i][k]):(_mazeA[i-1][k]+_maze[i][k]); else { if(_mazeA[i-1][k]!=0)_mazeA[i][k]=_mazeA[i-1][k]+_maze[i][k];/*The Last Row*/ else _mazeA[i][k]=0; } }else _mazeA[i][k]=_mazeA[i-1][k]+_maze[i][k];/*Left Boundary Element*/ }else _mazeA[i][k]=0;/*Block*/ if(_maze[k][i]>=0)/*Col Direction Element*/ { if(k>0)_mazeA[k][i]=(_mazeA[k][i-1]>_mazeA[k-1][i])?(_mazeA[k][i-1]+_maze[k][i]):(_mazeA[k-1][i]+_maze[k][i]); else _mazeA[k][i]=_mazeA[k][i-1]+_maze[k][i];/*Up Boundary Element*/ } else _mazeA[k][i]=0;/*Block*/ } if(i!=MaxSize-1)_mazeA[i][i]=(_mazeA[i-1][i]>_mazeA[i][i-1])?(_mazeA[i-1][i]+_maze[i][i]):(_mazeA[i][i-1]+_maze[i][i]); else{/*The Last Element*/ if(_mazeA[i-1][i]!=0)_mazeA[i][i]=_mazeA[i-1][i]+_maze[i][i];/*Can Reach*/ else _mazeA[i][i]=0;/*Can not Reach*/ } } return; } /// <summary> /// 利用Maze得出Maze的2维规划数组(动态规划) /// </summary> /// <param name="_maze"></param> /// <returns></returns> void SolveProblem(int (*_maze)[MaxSize]) { cout<<"Original Maze is Follow:(-1:can not pass),just can down and right direction to reach the bottom line......"<<endl; ShowMaze(_maze); int _mazeA[MaxSize][MaxSize]={0};/*Define the Assistant Maze*/ MakePlan_AsMaze(_maze,_mazeA);//Core Algorithm cout<<"Result Maze is Follow......"<<endl; ShowMaze<int>(_mazeA); return; } /// <summary> /// The Main Program /// </summary> /// <param name="argc"></param> /// <param name="argv"></param> /// <returns></returns> int main (int argc, char *argv[]) { SolveProblem(Maze); return(0); }  

【程序输出】

 

利用动态规划求迷宫的最优值问题_第1张图片

你可能感兴趣的:(Algorithm,算法,UP)