最短路径问题

#include <stdio.h>
#include <string.h>
#define _min(a, b) ((a) < (b) ? (a) : (b))

const int h[4][3] = {{3, 2, 3}, {2, 1, 4}, {3, 4, 5}, {3, 1, 2}};
const int v[3][4] = {{2, 2, 3, 4}, {4, 1, 2, 4}, {1, 2, 2, 3}};
int p[4][4];

void init() {
    memset(p, 0, sizeof (p));
}

int main() {
    int i, j;

    init();
    for (j = 1; j < 4; j++)
        p[0][j] = p[0][j - 1] + h[0][j - 1];
    for (i = 1; i < 4; i++)
        p[i][0] = p[i - 1][0] + v[i - 1][0];
    for (i = 1; i < 4; i++)
        for (j = 1; j < 4; j++)
            p[i][j] = _min(p[i - 1][j] + v[i - 1][j], p[i][j - 1] + h[i][j - 1]);
    printf("from p to a is %d\n", p[3][3]);
    for (i = 3; i >= 0; i--) {
        for (j = 0; j <= 3; j++)
            printf("%d ", p[i][j]);
        putchar('\n');
    }
    return 0;
}

你可能感兴趣的:(最短路径问题)