面试题20 顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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 class Solution { 2 public: 3 void printCircle(vector<vector<int> > matrix, int start, vector<int> &v){ 4 int rows = matrix.size(), columns = matrix[0].size(); 5 int endx = columns - 1 - start; 6 int endy = rows - 1 - start; 7 for (int i = start; i <= endx; i++) 8 v.push_back(matrix[start][i]); 9 if (start < endy){ 10 for (int i = start + 1; i <= endy; i++) 11 v.push_back(matrix[i][endx]); 12 } 13 if (start < endx && start < endy){ 14 for (int i = endx - 1; i >= start; i--) 15 v.push_back(matrix[endy][i]); 16 } 17 if (start < endx && start < endy - 1){ 18 for (int i = endy - 1; i >= start + 1; i--){ 19 v.push_back(matrix[i][start]); 20 } 21 } 22 } 23 24 vector<int> printMatrix(vector<vector<int> > matrix) { 25 vector<int> v; 26 int rows = matrix.size(), columns = matrix[0].size(); 27 int start = 0; 28 while (columns > start * 2 && rows > start * 2){ 29 printCircle(matrix, start, v); 30 start++; 31 } 32 return v; 33 } 34 };