顺时针打印矩阵
C++,老题了。
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> ans;
if (matrix.empty()) return ans;
int top = 0, bottom = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
int i = 0, j = 0;
while (left <= right && top <= bottom) {
for (i = top, j = left; j <= right; j++)
ans.push_back(matrix[i][j]);
top++;
if (top > bottom) break;
for (j = right, i = top; i <= bottom; i++)
ans.push_back(matrix[i][j]);
right--;
if (right < left) break;
for (i = bottom, j = right; j >= left; j--)
ans.push_back(matrix[i][j]);
bottom--;
if (top > bottom) break;
for (j = left, i = bottom; i >= top; i--)
ans.push_back(matrix[i][j]);
left++;
}
return ans;
}
};