剑指offer-19:顺时针打印矩阵
定义四个移动方向:上右下左(顺时针),从左上角开始遍历,先往右走,走到不能走位置,再更改下一个方向,再走到边界为止,依次类推,直至遍历n2个格子结束。
时间复杂度为O(n2)。
注意AC时需要考虑全局变量和局部变量的界定。
具体代码如下:
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
int n = matrix.size();
if(!n) return res; //opps
int 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 < n * m; i++){
res.push_back(matrix[x][y]);
st[x][y] = true;
int a = x + dx[d], b = y + dy[d]; //opps
if(a < 0 || a >= n || b < 0 || b >= m || st[a][b]){
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d]; //opps
}
x = a, y = b; //opps
}
return res;
}
};