54. Spiral Matrix
1. Description
Given an m x n matrix, return all elements of the matrix in spiral order.
2. Example
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[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]
3. Constraints
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
4. Solutions
My Accepted Solution
n is the number of values in i_matrix
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
vector<int> spiralOrder(const vector<vector<int>> &matrix) {
vector<int> elements(matrix.size() * matrix[0].size());
int element_index = 0;
for (int top = 0, left = 0, bottom = matrix.size() - 1, right = matrix[0].size() - 1;
element_index < elements.size();) {
for (int c = left; c <= right; ++c, ++element_index) {
elements[element_index] = matrix[top][c];
}
for (int r = top + 1; r <= bottom && element_index < elements.size();
++r, ++element_index) {
elements[element_index] = matrix[r][right];
}
for (int c = right - 1; c >= left && element_index < elements.size();
--c, ++element_index) {
elements[element_index] = matrix[bottom][c];
}
for (int r = bottom - 1; r > top && element_index < elements.size();
--r, ++element_index) {
elements[element_index] = matrix[r][left];
}
left++;
right--;
top++;
bottom--;
}
return elements;
}
};