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

题目:

题解:

Go 复制代码
var (
    dirs = [][]int{[]int{-1, 0}, []int{1, 0}, []int{0, -1}, []int{0, 1}}
    rows, columns int
)

func longestIncreasingPath(matrix [][]int) int {
    if len(matrix) == 0 || len(matrix[0]) == 0 {
        return 0
    }
    rows, columns = len(matrix), len(matrix[0])
    outdegrees := make([][]int, rows)
    for i := 0; i < rows; i++ {
        outdegrees[i] = make([]int, columns)
    }
    for i := 0; i < rows; i++ {
        for j := 0; j < columns; j++ {
            for _, dir := range dirs {
                newRow, newColumn := i + dir[0], j + dir[1]
                if newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] > matrix[i][j] {
                    outdegrees[i][j]++
                }
            }
        }
    }

    queue := [][]int{}
    for i := 0; i < rows; i++ {
        for j := 0; j < columns; j++ {
            if outdegrees[i][j] == 0 {
                queue = append(queue, []int{i, j})
            }
        }
    }
    ans := 0
    for len(queue) != 0 {
        ans++
        size := len(queue)
        for i := 0; i < size; i++ {
            cell := queue[0]
            queue = queue[1:]
            row, column := cell[0], cell[1]
            for _, dir := range dirs {
                newRow, newColumn := row + dir[0], column + dir[1]
                if newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] < matrix[row][column] {
                    outdegrees[newRow][newColumn]--
                    if outdegrees[newRow][newColumn] == 0 {
                        queue = append(queue, []int{newRow, newColumn})
                    }
                }
            }
        }
    }
    return ans
}
相关推荐
愚润求学10 小时前
【动态规划】01背包问题
c++·算法·leetcode·动态规划
dying_man13 小时前
LeetCode--44.通配符匹配
算法·leetcode
Paper Clouds13 小时前
代码随想录|图论|15并查集理论基础
数据结构·算法·leetcode·深度优先·图论
GGBondlctrl15 小时前
【leetcode】字符串,链表的进位加法与乘法
算法·leetcode·链表·字符串相加·链表相加·字符串相乘
打野二师兄16 小时前
LeetCode经典题解:21、合并两个有序链表
算法·leetcode·链表
前端拿破轮16 小时前
腾讯面试官:听说你在字节面试用栈实现队列,那怎么用队列实现栈呢?
算法·leetcode·面试
亚洲第一中锋_哈达迪18 小时前
详解缓存淘汰策略:LFU
后端·缓存·golang
nextera-void19 小时前
深入浅出 Golang:一次精神之旅
开发语言·golang·go
胡萝卜的兔1 天前
golang -gorm 增删改查操作,事务操作
开发语言·后端·golang
Y1nhl1 天前
力扣_二叉树的BFS_python版本
python·算法·leetcode·职场和发展·宽度优先