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

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

相关推荐
青山木16 小时前
Hot 100 --- 组合总和
java·数据结构·算法·leetcode
zander25816 小时前
LeetCode 46. 全排列
算法·leetcode·深度优先
会编程的土豆19 小时前
LeetCode 热题 HOT100(一):哈希表与双指针入门(Go 实现)
算法·leetcode·职场和发展
Tisfy19 小时前
LeetCode 3518.最小回文排列 II:试填法(组合数学)
算法·leetcode·题解·组合数学·计数·回文串·试填法
小poop1 天前
轮转数组:从暴力到最优,一题掌握算法复杂度分析
数据结构·算法·leetcode
玖玥拾1 天前
LeetCode 27 移除元素
算法·leetcode
hanlin032 天前
刷题笔记:力扣第704、977、209题(数组相关)
笔记·算法·leetcode
Rabitebla2 天前
C++ 内存管理全面复习:从内存分布到 operator new/delete
java·c语言·开发语言·c++·算法·leetcode
玖玥拾2 天前
LeetCode 58 最后一个单词的长度
算法·leetcode
hanlin032 天前
刷题笔记:力扣第19题-删除链表的倒数第N个结点
笔记·leetcode·链表