SGU 168

SGU 168,寻找矩阵中右上方,右方,下方最小的元素,采用动态规划解答。

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <map>
#include <string.h>
using namespace std;

int n, m;
int A[1005][1005];
int f[1005][1005];

int B(int u, int v) {
    int move[3][2] = {-1, 1, 0, 1, 1, 0};
    if (f[u][v] != 1234567) {
        return f[u][v];
    }
    int ans = A[u][v];
    //f[u][v] = A[u][v];
    for (int i = 0; i < 3; i++) {
        int uu = u + move[i][0];
        int vv = v + move[i][1];
        if (uu >= 0 && uu < n && vv >= 0 && vv < m) {
            ans = min(ans, B(uu, vv));
        }
    }
    return f[u][v] = ans;
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            scanf("%d", &A[i][j]);
            f[i][j] = 1234567;
        }
    }
    
    

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            printf("%d ", B(i, j));
        }
        printf("
");
    }

    //system("pause");
}
原文地址:https://www.cnblogs.com/litstrong/p/3224950.html