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
}
相关推荐
Swift社区4 小时前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt5555555555555 小时前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展
Q741_1476 小时前
C++ 模拟题 力扣495. 提莫攻击 题解 每日一题
c++·算法·leetcode·模拟
夏鹏今天学习了吗7 小时前
【LeetCode热题100(39/100)】对称二叉树
算法·leetcode·职场和发展
jiajixi7 小时前
Go 异步编程
开发语言·后端·golang
QX_hao7 小时前
【Go】--strings包
开发语言·后端·golang
秦禹辰8 小时前
venv与conda:Python虚拟环境深度解析助力构建稳定高效的开发工作流
开发语言·后端·golang
poemyang8 小时前
“不要通过共享内存来通信”——深入理解Golang并发模型与CSP理论
golang·并发编程
jiajixi8 小时前
go-swagger学习笔记
笔记·学习·golang