题目地址:https://leetcode-cn.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/

题目描述

n 座城市,从 0n-1 编号,其间共有 n-1 条路线。因此,要想在两座不同城市之间旅行只有唯一一条路线可供选择(路线网形成一颗树)。去年,交通运输部决定重新规划路线,以改变交通拥堵的状况。

路线用 connections 表示,其中 connections[i] = [a, b] 表示从城市 ab 的一条有向路线。

今年,城市 0 将会举办一场大型比赛,很多游客都想前往城市 0

请你帮助重新规划路线方向,使每个城市都可以访问城市 0 。返回需要变更方向的最小路线数。

题目数据 保证 每个城市在重新规划路线方向后都能到达城市 0

示例 1:

输入:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
输出:3
解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。

示例 2:

输入:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
输出:2
解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。

示例 3:

输入:n = 3, connections = [[1,0],[2,0]]
输出:0

提示:

  1. 2 <= n <= 5 * 10^4
  2. connections.length == n-1
  3. connections[i].length == 2
  4. 0 <= connections[i][0], connections[i][1] <= n-1
  5. connections[i][0] != connections[i][1]

题目大意

要让所有节点都能到达 0 节点,需要翻转多少个边?

解题方法

题目问的是所有顶点都能到节点 0 要翻转多少边。可以反过来,求从节点 0 出发到达所有顶点需要翻转多条边,于是就把多源问题转化成了单源问题。

但题目给出的是单向图,由于箭头是有向的,导致无法从节点 0 出发到达所有顶点。因此为了能让从节点 0 出发到达所有顶点,于是我们把单向图改成双向图,并且赋予不同的边不同的权重:题目给出的边的权重都是 1,我们添加的反向的边,权重都是 0 。

这样的目的是:我们从节点 0 出发,如果沿着题目给出的边走,权值为 1,即最终需要反向该边;如果沿着我们新添加的边走,权值为 0,即最终不需要反向该边。

如下图所示,直线是题目原本给出的边,权值为 1;曲线是自己添加的边,权值为 0。如果从节点 0 出发,需要沿着红色的路径,把所有的节点遍历一遍。累加次红色路径上所有的权值为 3,即如果让所有的点都能到达节点 0 ,需要翻转 3 条边。

遍历过程可以用 DFS 或者 BFS 两种做法完成。

DFS

记得需要使用 visited 保存已经遍历过的顶点,防止重复访问。

Python 代码如下:

class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
graph = collections.defaultdict(dict)
for con in connections:
graph[con[0]][con[1]] = 1
graph[con[1]][con[0]] = 0
visited = set()
return self.dfs(graph, 0, visited) def dfs(self, graph, cur, visited):
res = 0
visited.add(cur)
for nxt, value in graph[cur].items():
if nxt not in visited:
res += value
res += self.dfs(graph, nxt, visited)
return res

BFS

记得需要使用 visited 保存已经遍历过的顶点,防止重复访问。

class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
graph = collections.defaultdict(dict)
for con in connections:
graph[con[0]][con[1]] = 1
graph[con[1]][con[0]] = 0
queue = collections.deque()
queue.append(0)
visited = set()
res = 0
while queue:
cur = queue.popleft()
visited.add(cur)
for nxt, value in graph[cur].items():
if nxt not in visited:
res += value
queue.append(nxt)
return res

欢迎关注负雪明烛的刷题博客,leetcode刷题800多,每道都讲解了详细写法!

日期

2020 年 6 月 7 日 —— 今晚我来直播讲题

【LeetCode】1466. 重新规划路线 Reorder Routes to Make All Paths Lead to the City Zero (Python)的更多相关文章

  1. Vue 百度地图显示规划路线

    Vue 百度地图显示规划路线 1.首选引入相应的文件(建议单页面引入)(如有问题找上一篇博客园) 2.区别就是需要多引入几根不同的文件 import { BaiduMap, BmScale, BmGe ...

  2. [Swift]LeetCode815. 公交路线 | Bus Routes

    We have a list of bus routes. Each routes[i]is a bus route that the i-th bus repeats forever. For ex ...

  3. 调用高德地图web api 规划路线

    实现地图输出,出发地与目的地路线,效果如下 具体代码如下 <!doctype html> <html> <head> <meta charset=" ...

  4. 【Leetcode】【Medium】Reorder List

    Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do thi ...

  5. 个人.net学习规划路线

  6. LeetCode 143. 重排链表(Reorder List)

    题目描述 给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→… 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换. ...

  7. 【LeetCode】34. Find First and Last Position of Element in Sorted Array 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 二分查找 日期 题目地址:https://leetc ...

  8. 【LeetCode】714. Best Time to Buy and Sell Stock with Transaction Fee 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetc ...

  9. C#LeetCode刷题之#63-不同路径 II​​​​​​​(Unique Paths II)

    目录 问题 示例 分析 问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3682 访问. 一个机器人位于一个 m x ...

随机推荐

  1. C++匿名函数的使用

    c++匿名函数使用方法 1.匿名函数的使用 匿名函数的基本语法为: //[捕获列表](参数列表)->返回类型{函数体} int main() { auto Add = [](int a, int ...

  2. Browse Code Answers

    一个记录各种语言可能遇到的问题的论坛 :https://www.codegrepper.com/code-examples/

  3. 安卓手机添加系统证书方法(HTTPS抓包)

    目录 1. 导出证书(以Charles为例) 2. 安卓证书储存格式 3. 将导出的证书计算hash值 4. 生成系统系统预设格式证书文件 5. 上传证书 安卓7.0以后,安卓不信任用户安装的证书,所 ...

  4. C++你不知道的事

    class A { public: A() { cout<<"A's constructor"<<endl; } virtual ~A() { cout&l ...

  5. 腾讯云联合中国信通院&作业帮等首发《降本之源-云原生成本管理白皮书》

    在11月4日举办的2021腾讯数字生态大会云原生专场上,腾讯云联合中国信通院.作业帮等率先在国内重磅发布了<降本之源-云原生成本管理白皮书>(简称白皮书),基于腾讯云在业内最大规模的 Ku ...

  6. Azure Key Vault(二)- 入门简介

    一,引言 在介绍 Azure Key Vault 之前,先简单介绍一下 HSM(硬件安全模块). -------------------- 我是分割线 -------------------- 1,什 ...

  7. 日常Java 2021/10/5

    java 异常处理 Throwable中包括Error 和Exception,Exception包括IOException和RuntimeException 抛出异常 1.异常运算条件 Arithme ...

  8. Can we use function on left side of an expression in C and C++?

    In C, it might not be possible to have function names on left side of an expression, but it's possib ...

  9. Redis-5种基础数据结构

    Redis基础数据结构 知识整理源于<Redis深度历险 核心原理与应用实践>这本书 Redis 有的数据结构都以 唯一的 key 字符串作为名称,然后通过这个唯一 key 值来获取相应的 ...

  10. Django auth

    auth是django一个自带的用户验证系统,使用它可以减少我们的开发流程. 基本使用 大体流程: 自定义类 from django.contrib.auth.models import Abstra ...