【LeetCode】每日一题 2023_12_7 重新规划路线(DFS/BFS)

文章目录

刷题前唠嗑


LeetCode?启动!!!

这题好眼熟,怎么这几天都是这类问题!

题目:重新规划路线

题目链接:1466. 重新规划路线

题目描述

代码与解题思路

go 复制代码
func minReorder(n int, connections [][]int) (ans int) {
    g := make([][][]int, n)
    for _, v := range connections {
        x, y := v[0], v[1]
        // 第一个参数是正常存坐标, 第二个参数代表的是指向, 指向为 1 代表 x->y
        g[x] = append(g[x], []int{y, 1}) 
        g[y] = append(g[y], []int{x, 0})
    }
    var dfs func(int, int)
    dfs = func(cur, father int) {
        for _, v := range g[cur] {
            if v[0] != father { // 只向叶子节点 dfs
                if v[1] == 1 {  // 如果是从 0 节点方向往外指, 就让 ans++
                    ans++
                }
                dfs(v[0], cur)
            }
        }
    }
    dfs(0, -1)
    return ans
}

这道题目我思路的核心就是数箭头,举个例子:

从 0 到叶子节点有三个指向箭头,就需要改 3 条路:

从 0 到叶子节点有两个指向箭头,就需要改 2 条路:

从题目的红色修改箭头就能看出。

相关推荐
蒟蒻小袁30 分钟前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
GalaxyPokemon2 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
chao_7894 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表
岁忧7 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 上
sql·算法·leetcode
eachin_z7 小时前
力扣刷题(第四十九天)
算法·leetcode·职场和发展
飞川撸码10 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
_Itachi__18 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
chao_78919 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
编程绿豆侠21 小时前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划