敢教日月换新天。为有牺牲多壮志,

[Swift]LeetCode261.图验证树 $ Graph Valid Tree

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10227256.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.

For example:

Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.

Hint:

  1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
  2. According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.


给定n个标记为0到n-1的节点和一个无向边列表(每个边都是一对节点),编写一个函数来检查这些边是否构成有效的树。

例如:

如果n=5且边数为[[0,1],[0,2],[0,3],[1,4]],则返回true。

如果n=5且边数为[[0,1],[1,2],[2,3],[1,3],[1,4]],则返回false。

提示:

考虑到n=5和edges=[[0,1],[1,2],[3,4]],你应该返回什么?这是一个有效的树吗?

根据维基百科上树的定义:“树是一个无向图,其中任何两个顶点都由一条路径连接。换句话说,任何没有简单循环的连通图都是一棵树。”

注意:可以假定边中不会出现重复的边。因为所有边都是无向的,[0,1]与[1,0]相同,因此不会在边中一起出现。


 BFS 

复制代码
 1 class Solution {
 2     func validTree(_ n:Int,_ edges:[[Int]]) -> Bool{
 3         var g:[Set<Int>] = [Set<Int>](repeating:Set<Int>(),count:n)
 4         var s:Set<Int> = [0]
 5         var q:[Int] = [0]
 6         for a in edges
 7         {
 8             g[a[0]].insert(a[1]);
 9             g[a[1]].insert(a[0]);
10         }
11         while(!q.isEmpty)
12         {
13             var t:Int = q.first!
14             q.removeFirst()
15             for a in g[t]
16             {
17                 if s.contains(a)
18                 {
19                     return false
20                 }
21                 s.insert(a)
22                 q.append(a)
23                 g[a].remove(t)
24             }
25         }
26          return s.count == n
27     }
28 }
复制代码

 

posted @   为敢技术  阅读(292)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
哥伦布
09:09发布
哥伦布
09:09发布
3°
多云
东南风
3级
空气质量
相对湿度
47%
今天
中雨
3°/15°
周三
中雨
3°/13°
周四
小雪
-1°/6°