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
}
相关推荐
我的golang之路果然有问题2 小时前
云服务器部署Gin+gorm 项目 demo
运维·服务器·后端·学习·golang·gin
孔令飞3 小时前
Go 为何天生适合云原生?
ai·云原生·容器·golang·kubernetes
YGGP7 小时前
吃透 Golang 基础:数据结构之 Map
开发语言·数据结构·golang
march of Time7 小时前
go工具库:hertz api框架 hertz client的使用
开发语言·golang·iphone
dying_man8 小时前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel8 小时前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
余厌厌厌8 小时前
go语言学习 第9章:映射(Map)
服务器·学习·golang
roman_日积跬步-终至千里8 小时前
【Go语言基础【15】】数组:固定长度的连续存储结构
golang
GGBondlctrl9 小时前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想
cccc来财10 小时前
Go中的协程并发和并发panic处理
开发语言·后端·golang