递归--最长递增路径C语言实现代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))

int a[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
int path = 0;
int rows, cols;

int dps(int **matrix, int row, int col, int ** memory){

    if(memory[row][col] != 0){
        return memory[row][col];
    }

    memory[row][col]++;

    for (int i = 0; i < 4; ++i) {
        int dx = row + a[i][0];
        int dy = col + a[i][1];

        if(dx >= 0 && dx < rows && dy >= 0 && dy < cols && matrix[dx][dy] > matrix[row][col]){
            memory[row][col] = MAX(memory[row][col], dps(matrix, dx, dy, memory)+1);
        }
    }

    return memory[row][col];

}

void longestPath(int **matrix, int rowSize, int colSize){

    rows = rowSize;
    cols = colSize;

    int **memory = (int **) malloc(sizeof(int*) * rows);

    for (int i = 0; i < rows; ++i) {
        memory[i] = (int *) malloc(sizeof(int) * cols);
        memset(memory[i],0, sizeof(int)*cols);
    }

    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            path = MAX(path, dps(matrix,i,j,memory));
        }
    }

}

int main(){

    int a1[3] = {1,2,3};
    int a2[3] = {4,5,6};
    int a3[3] = {7,8,9};

    int *matrix[3] = {a1,a2,a3};

    longestPath(matrix,3,3);

    printf("longest path = %d",path);

    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值