LeetCode Spiral Matrix

LeetCode 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> vSpiralOrder;
if (matrix.size() == 0)return vSpiralOrder;
int sx = 0, sy = 0, tx = matrix.size(), ty = matrix[0].size();
while (true) {
for (int j = sy; j < ty; j++)
vSpiralOrder.push_back(matrix[sx][j]);
for (int i = sx + 1; i < tx; i++)
vSpiralOrder.push_back(matrix[i][ty - 1]);
for (int j = ty - 2; sx + 1 < tx && j >= sy; j--) // 满足上一个条件sx+1<tx
vSpiralOrder.push_back(matrix[tx - 1][j]);
for (int i = tx - 2; ty - 2 >= sy && i > sx; i--) // 满足上一个条件ty-2>=sy
vSpiralOrder.push_back(matrix[i][sy]);
sx++;
sy++;
tx--;
ty--;
if (sx >= tx || sy >= ty)break;
}
return vSpiralOrder;
}
};
```

```class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
if(matrix.empty() || matrix[0].empty()) return ans;
int start_row = 0, start_col = 0, end_row = matrix.size() - 1, end_col = matrix[0].size() - 1;
while(start_row <= end_row && start_col <= end_col) {
for(int j = start_col; j <= end_col; ++j) {
ans.push_back(matrix[start_row][j]);
}
++start_row;
for(int i = start_row; i <= end_row; ++i) {
ans.push_back(matrix[i][end_col]);
}
--end_col;
if(start_row <= end_row) { // 防止行向量
for(int j = end_col; j >= start_col; --j) {
ans.push_back(matrix[end_row][j]);
}
}
--end_row;
if(start_col <= end_col) { // 防止列向量
for(int i = end_row; i >= start_row; --i) {
ans.push_back(matrix[i][start_col]);
}
}
++start_col;
}
return ans;
}
};
```

1 thought on “LeetCode Spiral Matrix”

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