Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // main.m
- // DepthFirstSearcher
- //
- // Created by Diego Serrano on 3/3/15.
- // Copyright (c) 2015 diegoserranoa. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface Node : NSObject
- @property(nonatomic, strong) NSString *name;
- @property(nonatomic, strong) NSArray *children;
- -(id)initWithName:(NSString *)name;
- @end
- @implementation Node : NSObject
- -(id)initWithName:(NSString *)name{
- if (self = [self init]) {
- self.name = name;
- }
- return self;
- }
- @end
- Node* depthFirstSearchWithName(NSString *string, Node *parent){
- if ([parent.name isEqualToString:string]) {
- return parent;
- }
- for (Node* child in parent.children) {
- id returned = depthFirstSearchWithName(string, child);
- if (returned) {
- return returned;
- }
- }
- return nil;
- }
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- Node *a = [[Node alloc] initWithName:@"a"];
- Node *b = [[Node alloc] initWithName:@"b"];
- Node *c = [[Node alloc] initWithName:@"c"];
- Node *d = [[Node alloc] initWithName:@"d"];
- Node *e = [[Node alloc] initWithName:@"e"];
- Node *f = [[Node alloc] initWithName:@"f"];
- Node *g = [[Node alloc] initWithName:@"g"];
- Node *h = [[Node alloc] initWithName:@"h"];
- a.children = @[b, c];
- b.children = @[d, e, f];
- c.children = @[g];
- g.children = @[h];
- Node *result = depthFirstSearchWithName(@"g", a);
- NSLog(@"%@", result.name);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement