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