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
}
相关推荐
烧瓶里的西瓜皮1 小时前
Go语言从零构建SQL数据库(9)-数据库优化器的双剑客
数据库·sql·golang
李匠20242 小时前
C++GO语言微服务和服务发现②
开发语言·c++·golang·服务发现
YY_pdd4 小时前
使用go开发安卓程序
android·golang
_Itachi__4 小时前
LeetCode 热题 100 543. 二叉树的直径
java·算法·leetcode
追逐梦想之路_随笔5 小时前
gvm安装go报错ERROR: Failed to use installed version
开发语言·golang
海风极客5 小时前
《Go小技巧&易错点100例》第三十三篇
开发语言·后端·golang
pigfu5 小时前
go 通过汇编学习atomic原子操作原理
汇编·golang·atomic·缓存行·lock指令
Go高并发架构_王工7 小时前
从零到精通:GoFrame ORM 使用指南 - 特性、实践与经验分享
数据结构·经验分享·golang
Tisfy7 小时前
LeetCode 1550.存在连续三个奇数的数组:遍历
算法·leetcode·题解·数组·遍历
wang__123007 小时前
力扣70题解
算法·leetcode·职场和发展