#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;
}
递归--最长递增路径C语言实现代码
最新推荐文章于 2025-05-21 11:27:53 发布