Advertisement
HXXXXJ

Clone Graph

Mar 26th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.89 KB | None | 0 0
  1. /*graph,用什么data structure来存graph,楼主说了下,用dictionary key存node 然后value 是set<node>。还问了这个东西叫啥。。楼主一时没想起来叫adjacency 啥的。然后他给了些example让实现一个graph class。 写完后clone graph,
  2. 克隆的基本思路就是, 存 original node - clone node 的map,  然后BFS 所有的original node, 一次链接
  3. 如果所有node的label都是没有dup的话, 可以用label来做map key, 就不需要实现hashable
  4. */
  5.  
  6.  
  7. //BFS的实现方法。 注意不能重复进queue
  8. func cloneGraph(_ node: Node) -> Node{
  9.     // have to make node hashable inorder to put in map
  10.     var map = [Node: Node]()    // orignode - clone node
  11.     var queue = [Node]()
  12.     let head = Node(node.label)
  13.     map[node] = head
  14.  
  15.     while queue.count > 0 {
  16.         let cur = queue.removeFirst()
  17.         let clone = map[cur]! //只要进queue的肯定有克隆了
  18.         var nextList = [Node]()
  19.         for n in cur.neighbor {
  20.             if let next = map[n]{
  21.                 nextList.append(next)
  22.             }ellse {
  23.                 let next = Node(n.label)
  24.                 map[n] = next
  25.                 queue.append(n)
  26.                 nextList.append(next)
  27.             }
  28.         }
  29.         clone.neighbor = nextList
  30.     }
  31.     return head
  32. }
  33.  
  34. //DFS 的实现方法
  35. var map2 = [Node: Node]()
  36. func cloneGraphDFS(_ node: Node) -> Node{
  37.     if let copy = map2[node] {
  38.         return copy
  39.     }
  40.     let copy = Node(node.label)
  41.     map2[node] = copy
  42.    
  43.     for n in node.neighbor {
  44.         copy.neighbor.append(cloneGraphDFS(n))
  45.     }
  46.     return copy
  47. }
  48.  
  49. var copy = cloneGraphDFS(n1)
  50.  
  51.  
  52.  
  53.  
  54.  
  55. //实现hashable是为了把node放到map里面
  56. class Node : Hashable{
  57.     var neighbor = [Node]()
  58.     var label : String
  59.     init(_ l: String) {
  60.         label = l
  61.     }
  62.     static func == (ls: Node, rs: Node) -> Bool{
  63.         return ls.label == rs.label
  64.     }
  65.     var hashValue: Int {
  66.         return label.hashValue
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement