题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
注意边界,vector类型的vetctor时,即使塞入空的vector实例size()也不为零
#include <vector> class Solution { public: int step[4][2] = { 0, 1, 1, 0, 0, -1, -1, 0 }; vector<int> printMatrix(vector<vector<int> > matrix) { int n = matrix.size(); int m = matrix[0].size(); if(!n || !m) return {}; vector<int> ret; int i, j, l, r, t, d; i = j = l = t = 0; r = m - 1; d = n - 1; ret.push_back(matrix[0][0]); while (ret.size() != n * m) { for (auto& k : step) { while (ret.size() != n * m) { int x = i + k[0]; int y = j + k[1]; if (x > d) { r--; break; } else if (x < t) { l++; break; } if (y > r) { t++; break; } else if (y < l) { d--; break; } i = x, j = y; ret.push_back(matrix[i][j]); } } } return ret; } };