码迷,mamicode.com
首页 > 其他好文 > 详细

矩阵的最小路径和

时间:2018-03-18 22:26:32      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:时间复杂度   string   int   col   package   public   nbsp   空间   压缩   

 1 package coding;
 2 
 3 /**
 4  * Created by sakura on 2018/3/18.
 5  */
 6 public class Solution187 {
 7     public static void main(String[] args) {
 8         int[][] array={{1,3,5,9},{8,1,3,4},{5,0,6,1},{8,8,4,0}};
 9         System.out.println(minPathSum1(array));
10         System.out.println(minPathSum2(array));
11     }
12     
13     //时间复杂度O(M*N),空间复杂度O(M*N)
14     public static int minPathSum1(int[][] m){
15         if(m==null||m.length==0||m[0]==null||m[0].length==0){
16             return 0;
17         }
18         int row=m.length;
19         int col=m[0].length;
20         int[][] dp=new int[row][col];
21         dp[0][0]=m[0][0];
22 
23         for(int i=1;i<row;i++){
24             dp[i][0]=dp[i-1][0]+m[i][0];
25         }
26         for(int j=1;j<col;j++){
27             dp[0][j]=dp[0][j-1]+m[0][j];
28         }
29         for(int i=1;i<row;i++){
30             for(int j=1;j<col;j++){
31                 dp[i][j]=Math.min(dp[i-1][j],dp[i][j-1])+m[i][j];
32             }
33         }
34         return dp[row-1][col-1];
35     }
36     
37     //空间压缩,时间复杂度O(M*N),空间复杂度O(min{M,N})
38     public static int minPathSum2(int[][] m){
39         if(m==null||m.length==0||m[0]==null||m[0].length==0){
40             return 0;
41         }
42         int more=Math.max(m.length,m[0].length);
43         int less=Math.min(m.length,m[0].length);
44         boolean rowmore=more==m.length;
45         int[] arr=new int[less];
46         arr[0]=m[0][0];
47         
48         for(int i=1;i<less;i++){
49             arr[i]=arr[i-1]+(rowmore?m[0][i]:m[i][0]);
50         }
51         for(int i=1;i<more;i++){
52             arr[0]=arr[0]+(rowmore?m[i][0]:m[0][i]);
53             for(int j=1;j<less;j++){
54                 arr[j]=Math.min(arr[j-1],arr[j])
55                         +(rowmore?m[i][j]:m[j][i]);
56             }
57         }
58         return arr[less-1];
59     }
60 }

 

矩阵的最小路径和

标签:时间复杂度   string   int   col   package   public   nbsp   空间   压缩   

原文地址:https://www.cnblogs.com/sakura1027/p/8597670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!