本文共 3041 字,大约阅读时间需要 10 分钟。
Objective-C??BFS??????????????
Objective-C??????????????????iOS?macOS??????????????????Objective-C????????????BFS??????????????????????????????????????????????????????????Objective-C???BFS???
BFS???????????????????????????????????DFS????BFS????????????????????????????????????????
???????????BFS???????????????????????????????????Objective-C?????????????????????????????????
?????????BFS??????????????????????????????????????????????
???????BFS???????????????????????????????????????????????????????
????????????????????????????????????????????????????????????????????
?????BFS?????Objective-C?????
#import#import "Graph.h"@interface Graph : NSObject@property (nonatomic, assign) NSInteger nodeCount;@property (nonatomic, strong) NSMutableDictionary * adjacencyList;@end@implementation Graph- (void) initializeGraphWithNodes:(NSInteger)nodeCount { self.nodeCount = nodeCount; self.adjacencyList = [NSMutableDictionary new]; for (NSInteger i = 0; i < nodeCount; i++) { [self.adjacencyList setValue:[NSMutableArray new] forKey:[NSString stringWithFormat:@"%d", i]]; }}- (void) addEdgeBetweenNodes:(NSInteger)from to:(NSInteger)to { [[self.adjacencyList valueForKey:[NSString stringWithFormat:@"%d", from]] addObject:to]; [[self.adjacencyList valueForKey:[NSString stringWithFormat:@"%d", to]] addObject:from];}- (NSArray *) shortestPathFrom:(NSInteger)start to:(NSInteger)end { if (start == end) { return [NSArray arrayWithObject:@-1]; } BOOL *visited = [malloc sizeof(BOOL) * self.nodeCount]; visited[start] = true; NSInteger *distance = [malloc sizeof(NSInteger) * self.nodeCount]; distance[start] = 0; NSMutableArray *queue = [NSMutableArray new]; [queue addObject:start]; while (!queue.isEmpty) { NSInteger current = [queue.firstObject integerValue]; NSInteger currentIndex = current; for (NSInteger neighbor in [self.adjacencyList valueForKey:[NSString stringWithFormat:@"%d", currentIndex]]) { if (!visited[neighbor]) { visited[neighbor] = true; distance[neighbor] = distance[currentIndex] + 1; [queue addObject:neighbor]; } } [queue removeObjectAtIndex:0]; } if (!visited[end]) { return nil; } NSInteger current = end; NSMutableArray *path = [NSMutableArray new]; while (current != start) { [path addObject:[NSString stringWithFormat:@"%d", current]]; current = [distance objectAtIndex:current]; } [path reverse]; return path;}@end
Graph??????????Objective-C????????????????????????????????
initializeGraphWithNodes??????????????????????????
addEdgeBetweenNodes???????????????
shortestPathFrom???????????????????????????????????????
BFS?????????????????????????????????2D????????????????????BFS??????????????????????
BFS????????????????????????????????Objective-C???????????
转载地址:http://vdnfk.baihongyu.com/