Article Directory
Method 1: Simulation path: time O(nm), space O(1)
answer:
- The traversal method of the simulated matrix is divided into layers, printing layer by layer until the innermost element is printed
- Traverse the upper elements from left to right, from (top, left) to (top, right)
- Traverse the elements on the right from top to bottom, from (top + 1, right) to (bottom, right)
- If left <right && top <bottom, it means that it can be traversed to the left, from (bottom, right-1) to (bottom, left + 1). You can also traverse upwards, in order from (bottom, left) to (top + 1, left)
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector<int> board;
if (matrix.empty())
return board;
int top = 0, bottle = matrix.size() - 1, left = 0, right = matrix[0].size() - 1;
while (top <= bottle && left <= right)
{
for (int j = left; j <= right; j++)
{
board.push_back(matrix[top][j]);
}
for (int i = top + 1; i <= bottle; i++)
{
board.push_back(matrix[i][right]);
}
if (top < bottle && left < right)
{
for (int j = right - 1; j > left; j--)
{
board.push_back(matrix[bottle][j]);
}
for (int i = bottle; i > top; i--)
{
board.push_back(matrix[i][left]);
}
}
top++;
left++;
bottle--;
right--;
}
return board;
}
};