Hamsters dynamic programming of Pacman

Hamsters dynamic programming of Pacman

[On the subject] m * n squares, each cell to store a certain amount of beans, a hamster has been eating the lower left corner from the top right corner, but right or hamster can only go up. Hamsters do so much more than you can eat beans?
[Idea] as a hamster or can go up to the left, then the beans reach any point number consists of two parts: the point itself beans beans (x, y), max { Total beans reach the left path (x-1, y), the total number of beans arriving path (x, y-1) } below.
Thereby obtaining reach any point of the total number of beans formula P (x, y) = F (x, y) + max (P (x-1, y), P (x, y-1)). Calculate and record the total number of points for each of the beans, to avoid repeating the calculation, the calculated intermediate result storage path in the array.
【note】

  1. Because the matrix origin in the upper left corner, the formula needs to be transformed. P (x, y) = F (x, y) + max (P (x + 1, y), P (x, y-1));
  2. Note boundary value, here to note three points, the lower left corner, left margin, the lower boundary.
#include <stdio.h>
#include <stdlib.h>

int max(int a, int b) {
    if (a > b)
        return a;
    return b;
}

int main() {
    int m, n;
    int i, j;
    int **beans;
    int **path;

    scanf("%d %d", &m, &n); /* m * n矩阵 */

    beans = (int**)malloc(sizeof(void*) * m);
    path = (int**)malloc(sizeof(void*) * m);

    for (i = 0; i < m; i++) {
        beans[i] = (int*)malloc(sizeof(int) * n);
        path[i] = (int*)malloc(sizeof(int) * n);
    }

    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            scanf("%d", &beans[i][j]);
        }
    }

    printf("Beans:\n"); 
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%3d ", beans[i][j]); /* 显示矩阵上豆子数 */
        }
        printf("\n");
    }

    for (i = m - 1; i >= 0; i--) { /* to up */
        for (j = 0; j < n; j++) { /* to right */
            if (i == m - 1 && j == 0) { /* 左下角 */
                path[i][j] = beans[i][j];
            } else if (i != m - 1 && j == 0) { /* 左边界 */
                path[i][j] = beans[i][j] + path[i+1][j];
            } else if (i == m - 1 && j != 0) { /* 下边界 */
                path[i][j] = beans[i][j] + path[i][j-1];
            } else { /* 一般情况 */
                path[i][j] = beans[i][j] + max(path[i+1][j], path[i][j-1]);
            }
        }
    }

    printf("Path:\n");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%3d ", path[i][j]);
        }
        printf("\n");
    }
    printf("max path:%d\n", path[0][n-1]);

    for (i = 0; i < m; i++) {
        free(beans[i]);
        free(path[i]);
    }

    free(path);
    free(beans);
}

Guess you like

Origin www.cnblogs.com/xpl671/p/11986704.html