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;
}
相关推荐
liebe1*15 小时前
C语言程序代码(四)
c语言·数据结构·算法
夏鹏今天学习了吗6 小时前
【LeetCode热题100(56/100)】组合总和
算法·leetcode·职场和发展
chao1898446 小时前
C 文件操作全解速览
服务器·c语言·c#
微笑尅乐6 小时前
三种方法解开——力扣3370.仅含置位位的最小整数
python·算法·leetcode
青光键主7 小时前
C语言内功强化之const修饰指针
c语言·开发语言
hazy1k9 小时前
51单片机基础-TFT LCD 显示(ILI9341,SPI 4线)
c语言·stm32·单片机·嵌入式硬件·51单片机
奔跑吧邓邓子9 小时前
【C语言实战(63)】从0到1:51单片机GPIO控制实战秘籍
c语言·51单片机·开发实战·gpio控制实战
向前阿、11 小时前
数据结构从基础到实战——排序
c语言·开发语言·数据结构·程序人生·算法
Doro再努力11 小时前
数据结构04:链表的概念及实现单链表
c语言·数据结构
矮油0_o12 小时前
15.套接字和标准I/O
服务器·c语言·网络·网络编程·socket