Minimum Path Sum

- 日理万妓 2022-09-26 03:11 221阅读 0赞

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.

稍加改进变成一个简单版的迷宫问题。

  1. public static void main(String[] args) {
  2. int[][] a = new int[][]{
  3. {1,1,0,0,0},
  4. {1,3,1,0,1},
  5. {1,1,4,1,1},
  6. {0,2,0,1,0},
  7. {0,1,1,1,1}
  8. };
  9. search(a);
  10. }
  11. public static int search(int[][] a){
  12. if(a.length==0){
  13. return 0;
  14. }
  15. int r= a.length;
  16. int c= a[0].length;
  17. int[][] cost= new int[r][c];
  18. cost[0][0]=a[0][0];
  19. int flag=0;
  20. for (int i = 1; i < c; i++) {
  21. if(flag==1){
  22. cost[0][i]=Integer.MAX_VALUE;//表示此路不通
  23. }
  24. if(a[0][i]==0&&flag==0){
  25. cost[0][i]=Integer.MAX_VALUE;//表示此路不通
  26. flag=1;
  27. }
  28. if(flag==0){
  29. cost[0][i]=cost[0][i-1]+a[0][i];
  30. }
  31. }
  32. flag=0;
  33. for (int i = 1; i < r; i++) {
  34. if(flag==1){
  35. cost[i][0]=Integer.MAX_VALUE;
  36. }
  37. if(a[i][0]==0&&flag==0){
  38. cost[i][0]=Integer.MAX_VALUE;
  39. flag=1;
  40. }
  41. if(flag==0){
  42. cost[i][0]=cost[0][i-1]+a[i][0];
  43. }
  44. }
  45. for (int i =1 ; i < r; i++) {
  46. for (int j = 1; j < c; j++) {
  47. if(a[i][j]==0){
  48. cost[i][j]=Integer.MAX_VALUE;
  49. }else{
  50. if(cost[i-1][j]==Integer.MAX_VALUE&&cost[i][j-1]==Integer.MAX_VALUE){
  51. cost[i][j]=Integer.MAX_VALUE;
  52. }else{
  53. cost[i][j] = Math.min(cost[i-1][j], cost[i][j-1])+a[i][j];
  54. }
  55. }
  56. }
  57. }
  58. System.out.println(cost[r-1][c-1]);
  59. return cost[r-1][c-1];
  60. }

发表评论

表情:
评论列表 (有 0 条评论,221人围观)

还没有评论,来说两句吧...

相关阅读