标签:
Question:
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.
Analysis:
给出一个由非负数构成的 m * n 的网格,找出里面一条从左上角到右下角的最短路径。
注意:在每次行走的过程中,你只能往下或往右走。
public class Solution { public int minPathSum(int[][] rid) { if(rid == null || (rid.length == 0 && rid[0].length == 0)) return 0; if(rid.length == 1 && rid[0].length == 1) return rid[0][0]; int row = rid.length, col = rid[0].length; int[][] dp = new int[row][col]; dp[0][0] = rid[0][0]; for(int i=0; i<row; i++) { for(int j=0; j<col; j++) { if(i == 0 && j == 0) continue; else if(i == 0 && j != 0) dp[i][j] = dp[i][j-1] + rid[i][j]; else if(j == 0 && i != 0) dp[i][j] = dp[i-1][j] + rid[i][j]; else { dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j]) + rid[i][j]; } } } return dp[row-1][col-1]; } }
标签:
原文地址:http://www.cnblogs.com/little-YTMM/p/5215157.html