本文共 3278 字,大约阅读时间需要 10 分钟。
下面是一个使用Objective-C实现Dijkstra算法的完整示例。该示例包括一个简单图的表示以及Dijkstra算法的实现步骤。
首先,我们需要创建一个表示图的类。以下是实现的核心代码:
#import@interface Graph : NSObject@property (nonatomic, strong) NSMutableDictionary *adjacencyList;@end
Dijkstra算法是一种用于在图中找到从单一源点到所有其他节点的最短路径的算法。以下是实现步骤:
初始化:创建图的邻接列表,初始化源点的距离为0,其他节点的距离为无穷大。
优先队列:使用优先队列来按距离排序节点,确保每次处理距离最短的节点。
更新最短路径:对于每个节点,检查其邻接节点并更新其最短路径和距离。
以下是详细的实现步骤:
使用Objective-C中的NSDictionary来表示图的邻接列表。每个节点映射到一个数组,包含其邻接节点和相应的权重。
// 初始化邻接列表self.adjacencyList = [NSMutableDictionary new];
创建两个数组,分别用于存储每个节点的最短距离和路径。
// 初始化距离数组self.distances = [NSMutableDictionary new];// 初始化路径数组self.paths = [NSMutableDictionary new];// 初始化源点距离为0[self.distances setObject:@0 forKey:@(sourceNode)];
使用NSPriorityQueue来按距离排序节点,确保每次处理距离最短的节点。
// 创建优先队列NSPriorityQueue *priorityQueue = [NSPriorityQueue new];[self.priorityQueue enqueueObject:sourceNode];
提取最小距离节点:从优先队列中提取距离最小的节点。
更新邻接节点:对于该节点的每一个邻接节点,计算新的最短距离,并更新路径。
重复上述步骤,直到优先队列为空。
以下是完整的实现代码:
#import@interface Graph : NSObject@property (nonatomic, strong) NSMutableDictionary *adjacencyList;@end@implementation Graph- (void)dijsktraWithSourceNode:(int)sourceNode { // 初始化邻接列表 self.adjacencyList = [NSMutableDictionary new]; // 初始化距离和路径数组 self.distances = [NSMutableDictionary new]; self.paths = [NSMutableDictionary new]; // 初始化源点距离为0 [self.distances setObject:@0 forKey:@(sourceNode)]; // 初始化优先队列 NSPriorityQueue *priorityQueue = [NSPriorityQueue new]; [priorityQueue enqueueObject:sourceNode]; while (![priorityQueue isEmpty]) { // 提取距离最小的节点 id currentNode = [priorityQueue extractMinimum]; // 如果已经处理过该节点,跳过 if ([self.distances objectForKey:(currentNode)] != @0) { continue; } // 遍历所有邻接节点 for (id neighbor in [self.adjacencyList objectForKey:(currentNode)]) { int weight = [neighbor intValue]; int distance = [self.distances objectForKey:(currentNode)] + weight; if (distance < [self.distances objectForKey:(neighbor)]) { [self.distances setObject:distance forKey:(neighbor)]; [self.paths setObject:currentNode forKey:(neighbor)]; } // 如果路径已找到,跳过 if ([self.distances objectForKey:(neighbor)] == distance) { continue; } // 将邻接节点加入优先队列 [priorityQueue enqueueObject:neighbor]; } }}- (void)addEdgeWithSource:(int)source destination:(int)destination weight:(int)weight { // 添加边到邻接列表中 id existingEdge = [self.adjacencyList objectForKey:@(source)]; if (!existingEdge) { existingEdge = [NSMutableArray new]; } [existingEdge addObject:@{@"destination": destination, @"weight": weight}]; [self.adjacencyList setObject:existingEdge forKey:@(source)];}
Graph类:表示图的结构,包含邻接列表、距离和路径数组。
dijsktraWithSourceNode:核心算法方法,用于计算最短路径。
addEdgeWithSource:用于添加图中的边,支持多个边。
运行代码后,可以通过访问self.paths获取所有节点的最短路径信息。例如:
id destinationNode = @5;NSLog(@"最短路径:%@", [self.paths objectForKey:destinationNode]);
通过以上实现,您可以轻松在Objective-C中使用Dijkstra算法来解决最短路径问题。
转载地址:http://jeifk.baihongyu.com/