输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
一圈一圈地自外向内打印,最后一圈对单行/单列的情况做特别处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| class Solution { public: void printCircle(vector<vector<int> > &matrix, const int width, const int height, const int start, vector<int> &disk) { if (width == 1) { for (int x = start; x < start + height; x++) { disk.push_back(matrix[x][start]); } } else if (height == 1) { for (int y = start; y < start + width; y++) { disk.push_back(matrix[start][y]); } } else { for (int y = start; y < start + width - 1; y++) { disk.push_back(matrix[start][y]); } for (int x = start; x < start + height - 1; x++) { disk.push_back(matrix[x][start + width - 1]); } for (int y = start + width - 1; y > start; y--) { disk.push_back(matrix[start + height - 1][y]); } for (int x = start + height - 1; x > start; x--) { disk.push_back(matrix[x][start]); } } } vector<int> printMatrix(vector<vector<int> > matrix) { const int width = matrix[0].size(); const int height = matrix.size(); vector<int> result; if (width == 0 || height == 0) { return result; } else { int start = 0; while (width > start * 2 && height > start * 2) { printCircle(matrix, width - start * 2, height - start * 2, start, result); start++; } return result; } } };
|