64. Minimum Path Sum

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.

题目:从矩阵中找一条从左上角到右下角的路线,求最小路径和

思路:dp问题,dp[i][j]表示从左上节点走到[i,j]节点的最小路径和。注意在第一行时候只能从左往右走,第一列时候只能从上往下走。

 1     public int minPathSum(int[][] grid) {
 2         int m = grid.length;
 3         if (m == 0) return -1;
 4         int n = grid[0].length;
 5         if (n == 0) return -1;
 6         for (int i = 0; i < m; i++) {
 7             for (int j = 0; j < n; j++) {
 8                 if (i == 0 && j == 0)
 9                 {} else if (i == 0 && j > 0) {
10                     grid[0][j] = grid[0][j - 1] + grid[0][j];
11                 } else if (i > 0 && j == 0) {
12                     grid[i][0] = grid[i - 1][0] + grid[i][0];
13                 } else {
14                     grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j];
15                 }
16             }
17         }
18         return grid[m - 1][n - 1];      
19     }

 

posted @ 2017-10-16 10:52  daniel456  阅读(112)  评论(0编辑  收藏  举报