题目:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
代码:
class Solution {
public:
void backOrder(vector<vector<int>>& matrix, vector<int>& backorder, int starti, int startj, int m, int n)
{
if (starti >= m || startj >= n)
return;
for (int j = startj; j < n; j++)
backorder.push_back(matrix[starti][j]);
for (int i = starti + 1; i < m && n >= 1; i++)
backorder.push_back(matrix[i][n - 1]);
for (int j = n - 2; j >= startj && m - starti > 1; j--)
backorder.push_back(matrix[m - 1][j]);
for (int i = m - 2; i > starti && n - startj > 1; i--)
backorder.push_back(matrix[i][startj]);
return backOrder(matrix, backorder, starti + 1, startj + 1, m - 1, n - 1);
}
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int m = matrix.size();
if (m < 1)
return res;
int n = matrix[0].size();
backOrder(matrix, res, 0, 0, m, n);
return res;
}
};