Issue with DFS imlemtation in objetive-c
- by Hemant
i am trying to to do something like this
Below is my code:
-(id) init{
if( (self=[super init]) ) {
bubbles_Arr = [[NSMutableArray alloc] initWithCapacity: 9];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"1",@"1",@"1",@"1",@"1",nil] atIndex:0];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"3",@"3",@"5",@"5",@"1",nil] atIndex:1];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"3",@"5",@"3",@"1",nil] atIndex:2];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"3",@"5",@"3",@"1",nil] atIndex:3];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"1",@"1",@"1",@"1",@"1",nil] atIndex:4];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"5",@"3",@"5",@"1",nil] atIndex:5];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"5",@"5",@"5",@"5",nil] atIndex:6];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"5",@"5",@"5",@"5",nil] atIndex:7];
[bubbles_Arr insertObject:[NSMutableArray arrayWithObjects:@"5",@"5",@"5",@"5",@"5",nil] atIndex:8];
NOCOLOR = @"-1";
R = 9;
C = 5;
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(testting) userInfo:Nil repeats:NO];
}
return self;
}
-(void)testting{
// NSLog(@"dataArray---- %@",dataArray.description);
int startR = 0;
int startC = 0;
int color = 1 ;// red
// NSString *color = @"5";
//reset visited matrix to false.
for(int i = 0; i < R; i++)
for(int j = 0; j < C; j++)
visited[i][j] = FALSE;
//reset count
count = 0;
[self dfs:startR :startC :color :false];
NSLog(@"count--- %d",count);
NSLog(@"test--- %@",bubbles_Arr);
}
-(void)dfs:(int)ro:(int)co:(int)colori:(BOOL)set{
for(int dr = -1; dr <= 1; dr++)
for(int dc = -1; dc <= 1; dc++)
if((dr == 0 ^ dc == 0) && [self ok:ro+dr :co+dc]) // 4 neighbors
{
int nr = ro+dr;
int nc = co+dc;
NSLog(@"-- %d ---- %d",[[[bubbles_Arr objectAtIndex:nr] objectAtIndex:nc] integerValue],colori);
if ((([[[bubbles_Arr objectAtIndex:nr] objectAtIndex:nc] integerValue]==1 || [[[bubbles_Arr objectAtIndex:nr] objectAtIndex:nc] isEqualToString:@"1"]) && !visited[nr][nc])) {
visited[nr][nc] = true;
count++;
[self dfs:nr :nc :colori :set];
if(count>2)
{
[[bubbles_Arr objectAtIndex:nr] replaceObjectAtIndex:nc withObject:NOCOLOR];
[bubbles[nc+1][nr+1] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"gray_tiger.png"]];
}
}
}
}
-(BOOL)ok:(int)r:(int)c{
return r >= 0 && r < R && c >= 0 && c < C;
}
But it's only working for left to right,not working for right to left.
And it is also skipping first object.
Thanks in advance.