AcWing 40. 顺时针打印矩阵
原题链接
中等
作者:
andream7
,
2021-01-06 21:21:08
,
所有人可见
,
阅读 507
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
if (matrix.empty()) return res;
int n = matrix.size(), m = matrix[0].size();
vector<vector<bool>> st(n, vector<bool>(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
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;
}
};