fork(2) download
  1. //atul anand code :-
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<limits.h>
  5. #define size 5
  6.  
  7. int minA(int a , int b)
  8. {
  9.  
  10. return a > b ? b : a;
  11. }
  12.  
  13. int minB(int a,int b,int c)
  14. {
  15. if( a < b && a < c)
  16. return a;
  17. if(b < a && b < c)
  18. return b;
  19. if(c < a && c < b)
  20. return c;
  21. }
  22. int EulerProblem82(int mat[][size])
  23. {
  24.  
  25. int *sol=(int *)calloc(sizeof(int),size);
  26. int i,j,minVal;
  27.  
  28. for(i=0;i<size;i++)
  29. {
  30. sol[i]=mat[i][size - 1];
  31.  
  32. }
  33.  
  34. for(i=size-2;i>=0;i--)
  35. {
  36. j=0;
  37. // checking if it is min to go right or go down and then right
  38. sol[j]=minA((mat[j][i]+mat[j+1][i]+sol[j+1]),sol[j]+mat[j][i]);
  39.  
  40. for(j=1;j<size-1;j++)
  41. {
  42.  
  43. // checking if sol[j-1] has its minimum value by going right or go up and then right
  44. if(sol[j-1]!=(mat[j][i]+mat[j-1][i]+sol[j]))
  45. {
  46. //checking if min min is to go right or up and then right or down and then right
  47. sol[j]=minB(sol[j-1]+mat[j][i], sol[j]+mat[j][i],(mat[j][i]+mat[j+1][i]+sol[j+1]));
  48. }
  49. else
  50. {
  51. //if sol[j-1] took min path by going down and then right..hence no need to check up condition for sol[j]
  52. sol[j]=minA(sol[j]+mat[j][i],(mat[j][i]+mat[j+1][i]+sol[j+1]));
  53. }
  54.  
  55. }
  56. //checking if it is min to go right or go up and then right
  57. sol[j]=minA(sol[j-1]+mat[j][i] , sol[j]+mat[j][i]);
  58.  
  59. }
  60.  
  61. minVal=INT_MAX;
  62. for(i=0;i<size;i++)
  63. {
  64. if(sol[i] < minVal)
  65. {
  66. minVal=sol[i];
  67. }
  68. }
  69.  
  70. return minVal;
  71. }
  72.  
  73. int main()
  74. {
  75. int arr[][size]={{131,673,234,103,18},
  76. {201,96,342,965,150},
  77. {630,803,746,422,111},
  78. {537,699,497,121,956},
  79. {805,732,524,37,331}
  80. };
  81.  
  82.  
  83. printf("Minimum path value = %d\n\n",EulerProblem82(arr));
  84. return 0;
  85. }
Success #stdin #stdout 0.01s 1808KB
stdin
Standard input is empty
stdout
Minimum path value = 994