# [leetcode] Spiral Matrix

### Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

```[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
```

You should return `[1,2,3,6,9,8,7,4,5]`.

```class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> re;
int row = matrix.size();
if(row == 0){
return re; // empty input
}
int column = matrix[0].size();
int r = 0;
int c = 0;
while(row > 0 && column > 0){
//move right
for(int i = 0; i < column; i++){
re.push_back(matrix[r][c]);
c++;
}
c--;
r++;
if (--row == 0) break;
//move down
for(int i = 0; i < row; i++){
re.push_back(matrix[r][c]);
r++;
}
r--;
c--;
if (--column == 0) break;
//move left
for(int i = 0; i < column; i++){
re.push_back(matrix[r][c]);
c--;
}
c++;
r--;
if (--row == 0) break;
//move up
for(int i = 0; i < row; i++){
re.push_back(matrix[r][c]);
r--;
}
r++;
c++;
if (--column == 0) break;
}
return re;
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.