???-????????????????????????????????????????????????Objective-C?????????????????????
#import <Foundation/Foundation.h>
@interface Edge : NSObject
@property (nonatomic) NSInteger source;@property (nonatomic) NSInteger destination;@property (nonatomic) NSInteger weight;@end>@interface BellmanFord : NSObject
@property (nonatomic, strong) NSArray *edges;@property (nonatomic) NSInteger sourceNode;@property (nonatomic) NSInteger numberOfNodes;- (void)initializeDistances;
- (void)relaxEdge:(Edge *)edge;
- (void)bellmanFordAlgorithm;
- (void)printResults;@end>
@implementation BellmanFord
(void)initializeDistances
{self.distance = [NSArray array];for (NSInteger i = 0; i < numberOfNodes; i++){self.distance[i] = INFINITY;if (i == sourceNode){self.distance[i] = 0;}}}(void)relaxEdge:(Edge *)edge
{NSInteger u = edge.source;NSInteger v = edge.destination;NSInteger weight = edge.weight;if (distance[u] + weight < distance[v])
{distance[v] = distance[u] + weight;// ?????????????????}}(void)bellmanFordAlgorithm
{initializeDistances();for (NSInteger i = 0; i < numberOfNodes; i++){for (Edge *edge in edges){relaxEdge(edge);}}// ????????
// ???????????????while (true){Boolean updated = false;for (Edge *edge in edges){if (distance[edge.source] != INFINITY && distance[edge.destination] == INFINITY){distance[edge.destination] = distance[edge.source] + edge.weight;updated = true;}}if (!updated)
{break;}}printResults();
}(void)printResults
{NSLog(@"?????");for (NSInteger i = 0; i < numberOfNodes; i++){NSLog(@"?? %d ?????????? %f", i, distance[i]);}}??????????????`BellmanFord`???????-???????????????
???
- edges?????????
- sourceNode????
- numberOfNodes????????
?????
??????????????????????????????????????0?
???
??????????????????????????????????????????????????????????
?????
???-??????????????????????????????????????????????????????????
????
?????????????????????
????
??????????
BellmanFord *bellman = [[BellmanFord alloc] init]; bellman.sourceNode = 1; bellman.numberOfNodes = 4; bellman.edges = @[[Edge edgeWithSource:1 destination:2 weight:2], [Edge edgeWithSource:1 destination:3 weight:5], [Edge edgeWithSource:2 destination:3 weight:-1]]; [bellman bellmanFordAlgorithm];????????????????-???????????????????????????????????????????