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;
}
相关推荐
TANGLONG222几秒前
【C++】STL基础必备:深入解析vector容器的实现(含源码)
c语言·开发语言·数据结构·c++·笔记·算法·stl
50万马克的面包5 分钟前
C语言第3讲:分支和循环
c语言·开发语言·笔记·算法
承渊政道14 分钟前
【动态规划算法】(似包非包以及卡特兰数问题深入解析)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
人道领域25 分钟前
【LeetCode刷题日记】二叉树层序遍历完全指南:从基础到LeetCode实战一篇搞定BFS模板,秒杀4道经典面试题
java·开发语言·数据结构·leetcode·面试·二叉树
孬甭_28 分钟前
预处理详解
c语言·开发语言
承渊政道40 分钟前
【动态规划算法】(一文讲透二维费用的背包问题)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
2301_815279521 小时前
鸿蒙原生开发的“硬核通道”:ArkTS 与 C/C++ 高性能互操作全栈指南 —— FFI 机制深度解析与实战精要
c语言·c++·harmonyos
Je1lyfish10 小时前
CMU15-445 (2025 Fall/2026 Spring) Project#3 - QueryExecution
linux·c语言·开发语言·数据结构·数据库·c++·算法
墨染千千秋12 小时前
C/C++ Keywords
c语言·c++
爱编码的小八嘎15 小时前
C语言完美演绎9-23
c语言