【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 条路:

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

相关推荐
longlongzihan11 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
苦瓜打怪兽11 小时前
leetcode 热题100(11. 盛最多水的容器)
python·算法·leetcode
All for pursuit.16 小时前
【回溯-6】79.单词搜索
数据结构·c++·算法·leetcode
Navigator_Z16 小时前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode
旖旎夜光18 小时前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
longlongzihan18 小时前
回溯法详解:LeetCode 46. 全排列
算法·leetcode·回溯
圣保罗的大教堂20 小时前
leetcode 3532. 针对图的路径存在性查询 I 中等
leetcode
longlongzihan1 天前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
CQU_JIAKE2 天前
10.3【A】
深度优先
言乐62 天前
Python区分广度优先深度优先宽度优先的区别
python·算法·深度优先·广度优先·宽度优先