C语言 | Leetcode C语言题解之第329题矩阵中的最长递增路径

题目:

题解:

cpp 复制代码
const int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int rows, columns;

typedef struct point {
    int x, y;
} point;

int longestIncreasingPath(int** matrix, int matrixSize, int* matrixColSize) {
    if (matrixSize == 0 || matrixColSize[0] == 0) {
        return 0;
    }
    rows = matrixSize;
    columns = matrixColSize[0];

    int** outdegrees = (int**)malloc(sizeof(int*) * rows);
    for (int i = 0; i < rows; i++) {
        outdegrees[i] = (int*)malloc(sizeof(int) * columns);
        memset(outdegrees[i], 0, sizeof(int) * columns);
    }
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            for (int k = 0; k < 4; ++k) {
                int newRow = i + dirs[k][0], newColumn = j + dirs[k][1];
                if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] > matrix[i][j]) {
                    ++outdegrees[i][j];
                }
            }
        }
    }

    point* q = (point*)malloc(sizeof(point) * rows * columns);
    int l = 0, r = 0;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            if (outdegrees[i][j] == 0) {
                q[r++] = (point){i, j};
            }
        }
    }
    int ans = 0;
    while (l < r) {
        ++ans;
        int size = r - l;
        for (int i = 0; i < size; ++i) {
            point cell = q[l++];
            int row = cell.x, column = cell.y;
            for (int k = 0; k < 4; ++k) {
                int newRow = row + dirs[k][0], newColumn = column + dirs[k][1];
                if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] < matrix[row][column]) {
                    --outdegrees[newRow][newColumn];
                    if (outdegrees[newRow][newColumn] == 0) {
                        q[r++] = (point){newRow, newColumn};
                    }
                }
            }
        }
    }
    return ans;
}
相关推荐
JoJo_Way4 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
码农不惑5 小时前
2025.06.27-14.44 C语言开发:Onvif(二)
c语言·开发语言
凌肖战6 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
BreezeJuvenile7 小时前
数据结构与算法分析课设:一元多项式求值
c语言·课程设计·数据结构与算法分析·一元多项式计算
悲伤小伞8 小时前
linux_git的使用
linux·c语言·c++·git
GEEK零零七8 小时前
Leetcode 1103. 分糖果 II
数学·算法·leetcode·等差数列
气质、小青年!9 小时前
【排序算法】
c语言·数据结构
智者知已应修善业9 小时前
【51单片机节日彩灯控制器设计】2022-6-11
c语言·经验分享·笔记·单片机·嵌入式硬件·51单片机
重庆小透明10 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
开-悟10 小时前
嵌入式编程-使用AI查找BUG的启发
c语言·人工智能·嵌入式硬件·bug