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