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

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

相关推荐
ZC跨境爬虫1 小时前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
Navigator_Z2 小时前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
feilieren2 小时前
leetcode - 389. 找不同
算法·leetcode
evans在进步3 小时前
LeetCode 238 除自身以外数组的乘积:前缀积与后缀积详解
算法·leetcode·职场和发展
刃神太酷啦13 小时前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb
wenyq718 小时前
LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String
算法·leetcode
_Narcissus_20 小时前
分治&递归
数据结构·c++·笔记·算法·leetcode·递归·分治
青 春 记 忆1 天前
LeetCode 283. 移动零|Python 解法详解
python·算法·leetcode