题目描述:
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]
题源:here;完整实现:here
思路:
剥洋葱。我们像剥洋葱一样从外往内一层一层的输出。两种实现方案:1 单变量版;2 4变量版。4变量版的简洁和可读性远超单变量版。
实现1–单变量版
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.size() == 0) return result;
int rows = matrix.size(), cols = matrix[0].size();
if (rows == 1){
for (int i = 0; i < cols; i++) result.push_back(matrix[0][i]);
return result;
}
if (cols == 1){
for (int i = 0; i < rows; i++) result.push_back(matrix[i][0]);
return result;
}
for (int i = 0; i < min(rows, cols) / 2; i++){
for (int j = i; j < cols - i - 1; j++){
result.push_back(matrix[i][j]);
}
for (int j = i; j < rows - i - 1; j++){
result.push_back(matrix[j][cols-i-1]);
}
for (int j = i; j < cols - i - 1; j++){
result.push_back(matrix[rows-i-1][cols - j - 1]);
}
for (int j = i; j < rows - i - 1; j++){
result.push_back(matrix[rows - j - 1][i]);
}
}
if (cols >= rows && rows % 2){
for (int i = rows / 2; i < cols - rows/2; i++){
result.push_back(matrix[rows/2][i]);
}
}
else if (cols < rows && cols % 2){
for (int i = cols / 2; i < rows - cols/2; i++){
result.push_back(matrix[i][cols/2]);
}
}
return result;
}
实现2–4变量版
vector<int> spiralOrder_2(vector<vector<int>>& matrix){
vector<int> result; if (matrix.size() == 0) return result;
int left = 0, right = matrix[0].size() - 1, top = 0, bottom = matrix.size() - 1;
while (left <= right && top <= bottom){
for (int i = left; i < right; i++) result.push_back(matrix[top][i]);
for (int i = top; i <= bottom; i++) result.push_back(matrix[i][right]);
if (left < right && top < bottom){
for (int i = right - 1; i > left; i--) result.push_back(matrix[bottom][i]);
for (int i = bottom; i > top; i--) result.push_back(matrix[i][left]);
}
left++, right--, top++, bottom--;
}
return result;
}