Skip to content

Instantly share code, notes, and snippets.

@Altimor
Created October 26, 2013 07:15
Show Gist options
  • Save Altimor/7166276 to your computer and use it in GitHub Desktop.
Save Altimor/7166276 to your computer and use it in GitHub Desktop.
PIPOTW: Outward Counterclockwise Spiral Matrix Traversal
- (NSArray*)spirralArrayFromGridOfWidth:(int)width height:(int)height startline:(int)line column:(int)column{
NSMutableArray *returnArray = [NSMutableArray new];
int currentDirectionIndex = 0;
int currentInt;
int nextPivotal = 3;
int numOfPivotal = 1;
line++;
for(int i=1;i<=width*height; i++){
if(nextPivotal == i){
numOfPivotal++;
nextPivotal += ceil((float)numOfPivotal/2);
currentDirectionIndex++;
}
switch (currentDirectionIndex%4) {
case 0:
// Up
line--;
break;
case 1:
// Left
column--;
break;
case 2:
// Down
line++;
break;
case 3:
// Right
column++;
break;
}
currentInt = (line-1)*width+column;
if(currentInt<=0||line>height||column>width||!column||!line){
i--;
} else {
[returnArray addObject:[NSNumber numberWithInt:currentInt]];
}
}
return returnArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment