AcWing 40. 顺时针打印矩阵(蛇形数组)
原题链接
中等
作者:
Value
,
2020-09-05 09:55:03
,
所有人可见
,
阅读 659
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
int n = matrix.size();
if(n == 0) return res;
int m = matrix[0].size();
int cnt = 1, i, j;
i = j = 0;
bool flag[n][m];
memset(flag, false, sizeof flag);
while(cnt <= m * n){
while(j < m && !flag[i][j]){
res.push_back(matrix[i][j]);
flag[i][j ++ ] = true;
cnt ++ ;
}
j -- , i ++ ;
while(i < n && !flag[i][j]){
res.push_back(matrix[i][j]);
flag[i ++ ][j] = true;
cnt ++ ;
}
i -- , j -- ;
while(j >= 0 && !flag[i][j]){
res.push_back(matrix[i][j]);
flag[i][j -- ] = true;
cnt ++ ;
}
j ++ , i -- ;
while(i >= 0 && !flag[i][j]){
res.push_back(matrix[i][j]);
flag[i -- ][j] = true;
cnt ++ ;
}
i ++, j ++ ;
}
return res;
}
};