本文共 1185 字,大约阅读时间需要 3 分钟。
邻接表是一种有效的数据结构,通常用于表示稀疏图。在Objective-C中,开发邻接表可以通过NSMutableArray和NSDictionary轻松实现。以下将展示如何创建一个简单的图邻接表,包括添加边、打印图和遍历图的功能。
#import@interface Graph : NSObject@property (nonatomic, strong) NSMutableDictionary *edges;@end@implementation Graph- (void)addEdgeWithSource:(id)source destination:(id)destination { [self.edges setObject:destination forKey:source];}- (void)printGraph { for (id source in self.edges) { NSLog(@"源节点:%@,邻接节点:%@", source, self.edges[source]); }}- (void)traverseGraph { for (id source in self.edges) { NSLog(@"当前节点:%@,正在访问...", source); [self traverseFromSource:source markVisited:[NSMutableArray new]]; }}- (void)traverseFromSource:(id)source markVisited:(NSMutableArray *)visited { if (visited) { [visited removeObject:source]; } for (id neighbor in self.edges[source]) { if (! [visited containsObject:neighbor]) { [self traverseFromSource:neighbor markVisited:visited]; } }}
Graph类创建一个新的图邻接表实例。addEdgeWithSource:destination:方法,传递源节点和目标节点。printGraph方法,打印所有边及其对应的节点。traverseGraph方法,遍历所有节点并打印访问路径。通过上述方法,可以轻松地在Objective-C中实现图的邻接表表示和操作。
转载地址:http://knsfk.baihongyu.com/