54. Spiral Matrix

https://leetcode.com/problems/spiral-matrix/

Problem

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]

Solution

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ans;
        if (matrix.empty()) return ans;
        for (int i = 0; i < (min(matrix[0].size(), matrix.size())+ 1) / 2; i++){
            int x = i, y = i, width = matrix[0].size() - 2 * i, height = matrix.size() - 2 * i;
            for (int j = x; j < width + x; ++j) ans.push_back(matrix[y][j]);
            for (int j = y + 1; j < y + height - 1; ++j) ans.push_back(matrix[j][width + x - 1]);
            for (int j = width + x - 1; j >= x && height > 1; j--) ans.push_back(matrix[y + height - 1][j]);
            for (int j = y + height - 2; j > y && width > 1; j--) ans.push_back(matrix[j][x]);
        }
        return ans;
    }
};
  • #veryimportant

Last updated

Was this helpful?