我正在尝试实现此算法的Objective C实现。这里执行它:
@implementation DFSAlgorithm
-(void)dfs:(Graph*)g andStartingPosition:(int)s{
[self performDFS:g andPosition:s];
}
-(void)markedArrayInit:(int)capacity{
//0 is for unmarked vertices
//1 is form marked ones
self.marked=[[NSMutableArray alloc]initWithCapacity:capacity];
for(int i=0;i<[self.marked count];i++)
[self.marked replaceObjectAtIndex:i withObject:[NSNumber numberWithInt:0]];
}
-(void)performDFS:(Graph *)g andPosition:(int)v{
[self markedArrayInit:(int)[g numberOfVertices]];
[self.marked replaceObjectAtIndex:v withObject:[NSNumber numberWithInt:1]];
for (NSNumber *vertex in [g.vertices objectAtIndex:v]){
if(1==[self isMarked:v atGraph:g]){
NSLog(@"%d",(int)vertex);
[self performDFS:g andPosition:(int)vertex];
}
}
}
-(int)isMarked:(int)v atGraph:(Graph *)g{
return [self.marked objectAtIndex:v];
}
@end
但是,我不明白为什么会出现以下错误:
[__NSArrayM replaceObjectAtIndex:withObject:]: index 0 beyond bounds for empty array'
如何正确初始化标记的数组?
谢谢。
答案 0 :(得分:3)
NSMutableArray
被创建为空,您传递的容量值只是对实现有关您期望数组变大的暗示。
因此replaceObjectAtIndex:withObject:
对你不起作用,因为数组是空的,你没有要替换的对象。
而是仅使用addObject:
capacity
次。
答案 1 :(得分:1)
在markedArrayInit
方法中,您创建空的可变数组并为其保留内存,以保留至少capasity
个项目数。但是你实际上并没有向它添加任何东西(因为该方法中的循环实际上根本没有做任何事情)。要解决您的问题,您可以在for循环中添加足够数量的项目:
for (int i=0;i< initWithCapacity:capacity;i++)
[self.marked addObject: @0];
}
修改强> 您的实现还有其他几个问题:
在每次调用marked
时初始化performDFS:andPosition:
数组,并递归调用该方法。您应该将初始化移至dfs:andStartingPosition:
方法
在isMarked:atGraph:
方法中,您从数组中返回对象,而不是它保存的数值 - 因此它永远不会是1,您可能希望将其替换为以下实现(请注意,方法名称意味着我们返回一些布尔值,而不是我们稍后需要解释的整数):
-(BOOL)isMarked:(int)v atGraph:(Graph *)g {
return [self.marked[v] intValue] == 1;
}
...
if([self isMarked:v atGraph:g]){
...
}
有更好的数据结构来存储标记节点的索引,例如NSSet
或NSIndexSet
答案 2 :(得分:-1)
您尝试替换数组中不存在的对象。在markedArrayInit
中使用NSMutableArray中的addObject:
方法。循环中[self.marked count]
始终为0。