题目大意:将给出的二维数组螺旋输出
分析:数组考察。循环输出矩阵的每一层,用(x, y)(m, n)四个变量即左上角右下角两个坐标点维护四边边界即可,在每一层中分别输出上右下左四条边,每输出一层mn各减一,xy各加一。
代码:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
if (matrix.size() == 0) return ans;
int m = matrix.size() - 1;
int n = matrix[0].size() - 1;
for (int x = 0, y = 0;x <= m && y <= n;x++, y++) {
for (int j = y;j <= n;j++) {
ans.push_back(matrix[x][j]);
}
for (int j = x + 1;j <= m;j++) {
ans.push_back(matrix[j][n]);
}
for (int j = n - 1;j >= y && x != m;j--) {//x=m说明这层螺旋只有一行了,所以要避免重复添加
ans.push_back(matrix[m][j]);
}
for (int j = m - 1;j >= x + 1 && y != n;j--) {//y=n说明这层螺旋只有一列了,所以要避免重复添加
ans.push_back(matrix[j][y]);
}
m--;
n--;
}
return ans;
}
};