LeetCode_每日一题今日份_329.矩阵中的最长递增路径(没懂)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode_每日一题今日份_329.矩阵中的最长递增路径(没懂)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
const int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int rows, columns; //定義最終返回的最長遞增路勁數組的行、列int longestIncreasingPath(int** matrix, int matrixSize, int* matrixColSize) { //主if (matrixSize == 0 || matrixColSize[0] == 0) {return 0;}rows = matrixSize;columns = matrixColSize[0];int** memo = (int**)malloc(sizeof(int*) * rows); //分配行空間for (int i = 0; i < rows; i++) {memo[i] = (int*)malloc(sizeof(int) * columns); //分配列空間memset(memo[i], 0, sizeof(int) * columns); //分配最終返回的最長遞增路勁數組的空間}int ans = 0;for (int i = 0; i < rows; ++i) {for (int j = 0; j < columns; ++j) {ans = fmax(ans, dfs(matrix, i, j, memo)); //比較 求出最長遞增路徑}}free(memo);return ans;
}int dfs(int** matrix, int row, int column, int** memo) { //每個單元格的遞增路徑if (memo[row][column] != 0) {return memo[row][column];}++memo[row][column];for (int i = 0; i < 4; ++i) {int newRow = row + dirs[i][0], newColumn = column + dirs[i][1];if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] > matrix[row][column]) {memo[row][column] = fmax(memo[row][column], dfs(matrix, newRow, newColumn, memo) + 1);}}return memo[row][column];
}
總結
以上是生活随笔為你收集整理的LeetCode_每日一题今日份_329.矩阵中的最长递增路径(没懂)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java实例_综合实践5.简单工厂模式
- 下一篇: LeetCode.每日一题今日份_392