您的位置:首页 > 其它

Spiral Matrix

2016-02-28 22:43 323 查看
题目:

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]
.

cpp:

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.empty())
return result;
int m = matrix.size();
int n = matrix[0].size();
result.reserve(m * n);

int r = 0;
int c = 0;

int i;
while (r < m / 2 && c < n / 2) {
//left to right
for (i = c; i < n - c; i++) {
result.push_back(matrix[r][i]);
}
//up to down
for (i = r + 1; i < m - r; i++) {
result.push_back(matrix[i][n - c - 1]);
}
//right to left
for (i = n - c - 2; i >= c; i--) {
result.push_back(matrix[m - c - 1][i]);
}
//down to up
for (i = m - r - 2; i > r; i--) {
result.push_back(matrix[i][r]);
}
r++;
c++;
}

if (m >= n && 2*c < n) {
for (i = r; i < m - r; i++) {
result.push_back(matrix[i][c]);
}
}
if(m<n && 2*r < m){
for (i = c; i < n - c; i++) {
result.push_back(matrix[r][i]);
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: