AcWing 40. 顺时针打印矩阵
原题链接
中等
作者:
George
,
2020-11-19 00:09:00
,
所有人可见
,
阅读 356
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
if(!matrix.size() || !matrix[0].size()) return res;
int n = matrix.size(), m = matrix[0].size();
vector<vector<int>> st(n, vector<int>(m));
int dx[4]={-1, 0, 1, 0}, dy[4]={0, 1, 0, -1}, d = 1;
int x = 0, y = 0;
for(int k = 0; k < n*m; k++){
res.push_back(matrix[x][y]);
st[x][y] = true;
int a = x+dx[d], b = y+dy[d];
if(a<0 || a>=n || b<0 || b>=m || st[a][b]){
d = (1+d)%4;
a = x+dx[d], b = y+dy[d];
}
x = a, y = b;
}
return res;
}
};