AcWing 40. 顺时针打印矩阵
原题链接
中等
作者:
adamXu
,
2020-10-05 14:16:12
,
所有人可见
,
阅读 367
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
//为啥d改成2就不能通过了呢?明明是先往左边走的。。。
vector<int> res;
if(matrix.empty()) return res;
int n = matrix.size(),m = matrix[0].size();
vector<vector<bool>> st(n,vector(m,false));
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
int x = 0,y = 0,d = 1;
for(int i = 0;i < m * n;++i){
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 = (d + 1) % 4;
a =x + dx[d],b = y + dy[d];
}
x = a,y = b;
}
return res;
}
};