[Swift]LeetCode261.圖驗證樹 $ Graph Valid Tree

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-xmlcwinz-ma.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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.node

For example:git

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

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

Hint:app

  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的節點和一個無向邊列表(每一個邊都是一對節點),編寫一個函數來檢查這些邊是否構成有效的樹。this

例如:spa

若是n=5且邊數爲[[0,1],[0,2],[0,3],[1,4]],則返回true。code

若是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 }
相關文章
相關標籤/搜索