输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
class Solution { public: int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int x1, x2, y1, y2; bool in (int x, int y) { return x1 <= x && x < x2 && y1 <= y && y < y2; } void change (int k) { if (k == 0) x1++; else if (k == 1) y2--; else if (k == 2) x2--; else y1++; } vector<int> printMatrix(vector<vector<int> > g) { if (!g.size() || !g[0].size()) return {}; x2 = g.size(), y2 = g[0].size(); int len = x2 * y2; vector<int> ans; int x = 0, y = -1, k = 0; for (int i = 0; i < len; i++) { x += dx[k], y += dy[k]; if (in(x, y)) { ans.push_back(g[x][y]); } else { x -= dx[k], y -= dy[k]; change(k); k = (k + 1) % 4; x += dx[k], y += dy[k]; ans.push_back(g[x][y]); } } return ans; } };
标签:顺时针,int,打印,矩阵,dx,ans,dy,y2,size From: https://www.cnblogs.com/leetothemoon/p/16983908.html