Advertisement
LA77

Untitled

Oct 23rd, 2024
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. /* file: side.c */
  2. /* author: Anastase Luca-George (email: l.anastase@student.rug.nl) */
  3. /* date: 10/23/2024 */
  4. /* version: 1.0 */
  5. /* Description: This program prints the minimum-cost path in a grid given some specifications */
  6.  
  7. #include <stdio.h>
  8.  
  9. #define NMAX 1005
  10.  
  11. int n, m;
  12. int mat[NMAX][NMAX];
  13. int dp[NMAX][NMAX];
  14.  
  15. // Function to return the minimum of two integers
  16. int mini(int x, int y) {
  17. if(x > y) {
  18. return y;
  19. }
  20. return x;
  21. }
  22.  
  23. int main(){
  24. // Read the dimensions of the matrix
  25. scanf("%d%d", &n, &m);
  26.  
  27. // Read the input matrix values
  28. for(int i = 1; i <= n; ++i) {
  29. for(int j = 1; j <= m; ++j) {
  30. scanf("%d", &mat[i][j]);
  31. }
  32. }
  33.  
  34. // Initialize the DP table with a large value (infinity equivalent)
  35. for(int i = 0; i <= n + 1; ++i) {
  36. for(int j = 0; j <= m + 1; ++j) {
  37. dp[i][j] = 10000000;
  38. }
  39. }
  40.  
  41. // Base case: Set the last column of dp to the corresponding values in mat
  42. for(int i = 1; i <= n; ++i) {
  43. dp[i][m] = mat[i][m];
  44. }
  45.  
  46. // Build the DP table from right to left (from column m-1 to 1)
  47. for(int j = m - 1; j >= 1; --j) {
  48. for(int i = 1; i <= n; ++i) {
  49. dp[i][j] = mini(dp[i+1][j+1], mini(dp[i][j+1], dp[i-1][j+1])) + mat[i][j];
  50. }
  51. }
  52.  
  53. int min = 10000000;
  54.  
  55. // Find the minimum cost starting from the first column
  56. for(int i = 1; i <= n; ++i) {
  57. if(dp[i][1] < min) {
  58. min = dp[i][1];
  59. }
  60. }
  61.  
  62. // Output the minimum cost
  63. printf("%d\n", min);
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement