Advertisement
Guest User

Untitled

a guest
Apr 21st, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. //
  2. // main.m
  3. // DepthFirstSearcher
  4. //
  5. // Created by Diego Serrano on 3/3/15.
  6. // Copyright (c) 2015 diegoserranoa. All rights reserved.
  7. //
  8.  
  9. #import <Foundation/Foundation.h>
  10.  
  11. @interface Node : NSObject
  12.  
  13. @property(nonatomic, strong) NSString *name;
  14. @property(nonatomic, strong) NSArray *children;
  15.  
  16. -(id)initWithName:(NSString *)name;
  17.  
  18. @end
  19. @implementation Node : NSObject
  20.  
  21. -(id)initWithName:(NSString *)name{
  22. if (self = [self init]) {
  23. self.name = name;
  24. }
  25. return self;
  26. }
  27.  
  28. @end
  29.  
  30.  
  31. Node* depthFirstSearchWithName(NSString *string, Node *parent){
  32. if ([parent.name isEqualToString:string]) {
  33. return parent;
  34. }
  35.  
  36. for (Node* child in parent.children) {
  37. id returned = depthFirstSearchWithName(string, child);
  38. if (returned) {
  39. return returned;
  40. }
  41. }
  42. return nil;
  43. }
  44.  
  45. int main(int argc, const char * argv[]) {
  46. @autoreleasepool {
  47. Node *a = [[Node alloc] initWithName:@"a"];
  48. Node *b = [[Node alloc] initWithName:@"b"];
  49. Node *c = [[Node alloc] initWithName:@"c"];
  50. Node *d = [[Node alloc] initWithName:@"d"];
  51. Node *e = [[Node alloc] initWithName:@"e"];
  52. Node *f = [[Node alloc] initWithName:@"f"];
  53. Node *g = [[Node alloc] initWithName:@"g"];
  54. Node *h = [[Node alloc] initWithName:@"h"];
  55.  
  56. a.children = @[b, c];
  57. b.children = @[d, e, f];
  58. c.children = @[g];
  59. g.children = @[h];
  60.  
  61. Node *result = depthFirstSearchWithName(@"g", a);
  62. NSLog(@"%@", result.name);
  63.  
  64. }
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement