【问题标题】:Logically determine shortest path逻辑确定最短路径
【发布时间】:2015-11-24 02:14:45
【问题描述】:

到目前为止,我已经为位置创建了所有名称,现在我正在编写一个方法,该方法将为达到最终目标所需的“位置”返回一个数组。然后,该数组将用于确定到达那里应该花费多少“时间”的方法。但是,我现在无法确定逻辑路径的方法。

因此,每个位置都会有它连接到的相对位置。示例;

NSArray *posAlphaConnections = [[NSArray alloc] initWithObjects:@"posDelta",@"posBravo",@"posFoxtrot", nil];

NSDictionary *posAlpha = @{@"connections":posAlphaConnections,
                           @"time":positionCrossTimeAlpha};

_positions = @{     @"posAlpha":posAlpha,
                    @"posBra....
                    }; //NSDictionary

所以你最终得到了一条途径

问题是

-(NSArray *)returnPathWithPlayer:(PlayerClass *)player andGoal:(NSString *)goal {

    NSString *currentPosition = player.position;

    //Up to here

    return 0;
}

我目前正在考虑..我应该为每个可能的连接运行一个循环..在每个可能的下一个连接中,直到达到目标,然后保持返回最短距离的路线..?然后使用那条路线。但是,我无法从逻辑上想到如何写。

PS:我还要补充一点,每个位置都有一个大小变量,用于跨越该位置所需的“时间长度”。所以这也应该考虑到,而不是最少的职位,最少的时间应该是优先考虑的。

编辑:

-(NSArray *)returnPathWithPlayer:(PlayerClass *)player andGoal:(NSString *)goal {

    NSString *currentPosition = player.position;

    NSLog(@"current Position %@", currentPosition);

    NSArray *connections = [[_positions valueForKey:currentPosition] valueForKey:@"connections"];

    __block BOOL pathFound = false;

    for (int i = 0; i < [connections count]; i++) {
        if ([connections[i] isEqualToString:goal]) {
            pathFound = true;
        } else {
            for (int j = 0; j < [[[_positions valueForKey:connections[i]] valueForKey:@"connections"] count]; j++) {
                if ([[[_positions valueForKey:connections[i]] valueForKey:@"connections"][j] isEqualToString:goal]) {
                    pathFound = true;
                }
            }
        }
    }

    if (pathFound) {
        NSLog(@"path to %@ found", goal);
    } else {
        NSLog(@"path to %@ not-found", goal);
    }

    return 0;
}

这是我的逻辑所引向我的地方,但是,其他每个都将代表一种新的可能性。这可能比我预期的要多。那么我怎样才能写得更好?

【问题讨论】:

    标签: ios objective-c loops logic path-finding


    【解决方案1】:

    您正在寻找图中两个节点之间的最短路径。 Dijkstra's Algorithm 是针对这个问题的一个很好且简单的广度优先搜索。

    【讨论】:

    • @Daniel:我看到了你的编辑,文本对我来说毫无意义,我不会尝试对代码进行逆向工程。
    • 好的,感谢您提供算法。我敢肯定它适合 99% 的这种情况。
    猜你喜欢
    • 2013-10-18
    • 2015-04-11
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 2012-02-04
    • 2020-05-11
    相关资源
    最近更新 更多