Given an m x n
matrix, return all elements of the matrix in spiral order.
To solve this problem, we will use a simulation approach, where we simulate the process of traversing the matrix in spiral order. The matrix can be traversed layer by layer, and in each layer we can follow a specific direction order: right, down, left, and up. We keep track of our boundaries to know when to change direction. Here’s the detailed strategy:
#include <vector>
std::vector<int> spiralOrder(const std::vector<std::vector<int>>& matrix) {
if(matrix.empty()) return {};
int m = matrix.size();
int n = matrix[0].size();
std::vector<int> result;
int left = 0;
int right = n - 1;
int top = 0;
int bottom = m - 1;
while (left <= right && top <= bottom) {
// Traverse from left to right along the top row
for (int col = left; col <= right; ++col) {
result.push_back(matrix[top][col]);
}
++top; // Move the top boundary down
// Traverse from top to bottom along the right column
for (int row = top; row <= bottom; ++row) {
result.push_back(matrix[row][right]);
}
--right; // Move the right boundary to the left
if (top <= bottom) { // Check if we still have rows to process
// Traverse from right to left along the bottom row
for (int col = right; col >= left; --col) {
result.push_back(matrix[bottom][col]);
}
--bottom; // Move the bottom boundary up
}
if (left <= right) { // Check if we still have columns to process
// Traverse from bottom to top along the left column
for (int row = bottom; row >= top; --row) {
result.push_back(matrix[row][left]);
}
++left; // Move the left boundary to the right
}
}
return result;
}
The time complexity of this solution is O(m * n), where m
is the number of rows and n
is the number of columns. This is because every element in the matrix is visited exactly once. The space complexity is O(1) (excluding the space required for the output list), as we only use a few additional variables to manage the boundaries and directions.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?