标签:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
利用动态规划,对于点[i,j]来说,dp[i][j] = min(dp[i-1][j],dp[i][j-1])+grid;初始化边界值,不断的迭代就可以获得最终解。
int minPath(vector<vector<int> >& grid){ int column = grid[0].size(); int row = grid.size(); int** dp = new int*[row]; for(int i=0;i<row;i++){ dp[i] = new int[column]; } for(int i=0;i<row;i++) for(int j=0;j<column;j++) dp[i][j] = 0; dp[0][0] = grid[0][0]; for(int j=1;j<column;++j)//初始化边界 dp[0][j] = dp[0][j-1]+grid[0][j]; for(int i=1;i<row;++i) dp[i][0] = dp[i-1][0]+grid[i][0]; for(int i=1;i<row;++i) for(int j=1;j<column;++j) dp[i][j] = min(dp[i-1][j],dp[i][j-1])+grid[i][j]; int result = dp[row-1][column-1]; for(int j=0;j<row;j++) delete[] dp[j]; delete[] dp; return result; } int main(){ //int mp = 5; vector<vector<int> > mp; vector<int> temp; for(int i=0;i<4;++i){ for(int j=0;j<5;++j){ int ss = rand()%8; cout<<ss<<" "; temp.push_back(ss); } cout<<endl; mp.push_back(temp); temp.clear(); } int num_pow = minPath(mp); cout<<num_pow<<endl; }
标签:
原文地址:http://www.cnblogs.com/zhang-wen/p/4797047.html