Advertisement
bayareabelletrist

Deep copy cyclic graph

Jul 21st, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. @interface GraphNode : NSObject
  2. @property (nonatomic, copy) NSArray<GraphNode *> *neighbors;
  3. @property (nonatomic, copy) NSString *name;
  4. @end
  5.  
  6. @interface Graph : NSObject<NSCopying>
  7. @property (nonatomic, copy) NSArray<GraphNode *> *nodes;
  8. @end
  9.  
  10. @implementation GraphNode
  11. - (instancetype)init {
  12.     self = [super init];
  13.     if(self) {
  14.         _neighbors = [NSMutableArray new];
  15.     }
  16.     return self;
  17. }
  18. @end
  19.  
  20. @implementation Graph
  21. - (instancetype)init {
  22.     self = [super init];
  23.     if(self) {
  24.         _nodes = [NSMutableArray new];
  25.     }
  26.     return self;
  27. }
  28. - (id)copyWithZone:(NSZone *)zone {
  29.     NSMutableArray<GraphNode *> *copiedNodes = [NSMutableArray new];
  30.     NSMutableDictionary<NSString *, GraphNode *> *copies = [NSMutableDictionary new];
  31.     for(GraphNode *node in self.nodes) {
  32.         GraphNode *copied = [GraphNode new];
  33.         copied.name = node.name;
  34.         copied.neighbors = [node.neighbors copy];
  35.         [copiedNodes addObject:copied];
  36.         copies[node.name] = copied;
  37.     }
  38.     for(GraphNode *node in self.nodes) {
  39.         NSMutableArray<GraphNode *> *copiedNeighbors = [NSMutableArray new];
  40.         for(GraphNode *neighbor in node.neighbors) {
  41.             [copiedNeighbors addObject:copies[neighbor.name]];
  42.         }
  43.         copies[node.name].neighbors = copiedNeighbors;
  44.     }
  45.    
  46.     Graph *copy = [Graph new];
  47.     copy.nodes = copiedNodes;
  48.     return copy;
  49. }
  50. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement