题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
#include <cstring> #include <vector> class Solution { public: int idx=0; int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; void changeDir(){ idx=(idx+1)%4; } int used[110][110]; vector<int> printMatrix(vector<vector<int> > matrix) { memset(used, 0, sizeof used); int i=0,j=0; vector<int> res; while(res.size() < matrix[0].size() * matrix.size()){ if(i<0 || i>=matrix.size() || j<0 || j>=matrix[0].size() || used[i][j]){ i = i - dx[idx]; j = j - dy[idx]; changeDir(); }else{ res.push_back(matrix[i][j]); used[i][j] = 1; } i = i + dx[idx]; j = j + dy[idx]; } return res; } };