Created
November 4, 2013 18:25
-
-
Save wuoix/7307034 to your computer and use it in GitHub Desktop.
Coding Interviews Spiral Code Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int * spiral(int r, int c, int sr, int sc) { | |
//Traverse direction increment state and direction state | |
// %4 == 1 -> north; 2 -> east; 3 -> south; 0 -> west; | |
int *array = new int [r*c]; | |
int counter = 1, steps, dir, increment, arridx = 0; | |
bool vertical = true; | |
array[arridx++] = matrix[sr-1][sc-1]; | |
while(arridx < r*c) { | |
dir = counter % 4; | |
vertical = dir == 1 || dir == 3 ? true : false; | |
if (vertical) | |
increment = dir == 1 ? -1 : 1; | |
else | |
increment = dir == 0 ? 1 : -1; | |
for (int i = 0; i < (counter+1)/2; i++) { | |
if (vertical) | |
sr += increment; | |
else | |
sc += increment; | |
if (sr <= r && sr >= 1 && sc <= c && sc >= 1) { | |
array[arridx++] = matrix[sr-1][sc-1]; | |
} | |
} | |
counter++; | |
} | |
return array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment