54. 螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int left = 0, right = matrix[0].size()-1, top = 0, bottom = matrix.size()-1;
vector<int> ans;
while(left<right&&top<bottom){
for (int i = left; i < right; ++i) ans.push_back(matrix[top][i]);
for (int i = top; i < bottom; ++i) ans.push_back(matrix[i][right]);
for (int i = right; i > left; --i) ans.push_back(matrix[bottom][i]);
for (int i = bottom; i > top; --i) ans.push_back(matrix[i][left]);
++left, --right, ++top, --bottom;
}
// 中间只有一个元素
if (left == right && top == bottom){
ans.push_back(matrix[top][left]);
return ans;
}
// 还有一列元素没有被放进去
// 1 2 3
// 4 5 6
// 7 8 9
// 1 2 3
while(left==right && top<=bottom){
ans.push_back(matrix[top++][left]);
}
// 还有一行元素没有被放进去
// 1 2 3 4
// 5 6 7 8
// 9 0 1 2
while(top==bottom && left<=right){
ans.push_back(matrix[top][left++]);
}
return ans;
}
};
59. 螺旋矩阵 II
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, 0));
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int num = 1;
while(left < right){
for (int i = left; i < right; ++i) ans[top][i] = num++;
for (int i = top; i < bottom; ++i) ans[i][right] = num++;
for (int i = right; i > left; --i) ans[bottom][i] = num++;
for (int i = bottom; i > top; --i) ans[i][left] = num++;
++left, --right, ++top, --bottom;
}
// 判断中间是否有元素
if (n%2)
ans[top][left] = num;
return ans;
}
};