Created
February 13, 2018 23:27
-
-
Save jianminchen/4bcf016e1d2bd95545dd80e0ece5635b to your computer and use it in GitHub Desktop.
Leetcode 54 - spiral matrix - Using directions - 2015 June
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
/* | |
Julia chose the blog to study Leetcode 54: Spiral matrix on June 11, 2015. | |
http://gongxuns.blogspot.ca/2012/12/leetcode-spiral-matrix.html | |
*/ | |
vector<int> spiralOrder(vector<vector<int> > &matrix) { | |
vector<int> result; | |
int row = matrix.size(); | |
if(row == 0) return result; | |
int col = matrix[0].size(); | |
if(col == 0) return result; | |
//define the step for 4 directions | |
int x[4] = { 1, 0, -1, 0 }; | |
int y[4] = { 0, 1, 0, -1 }; | |
int visitedRows = 0; | |
int visitedCols = 0; | |
// define direction: 0 means up, 1 means down, 2 means left, 3 means up | |
int direction = 0; | |
int startx = 0, starty = 0; | |
int candidateNum = 0, moveStep = 0; | |
while (true) | |
{ | |
if (x[direction] == 0) // visit y axis | |
candidateNum = row - visitedRows; | |
else // visit x axis | |
candidateNum = col - visitedCols; | |
if (candidateNum <= 0) | |
break; | |
result.push_back(matrix[starty][startx]); | |
moveStep++; | |
if (candidateNum == moveStep) // change direction | |
{ | |
visitedRows += x[direction] == 0 ? 0 : 1; | |
visitedCols += y[direction] == 0 ? 0 : 1; | |
direction = (direction + 1) % 4; | |
moveStep = 0; | |
} | |
startx += x[direction]; | |
starty += y[direction]; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment