本文为剑指 offer 系列第二十一篇。
给定一个矩阵,顺时针将数据打印出来,没有特殊的难点,主要就是为了考察耐心和细心程度。
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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
| class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { int rows = matrix.size(); int cols = matrix[0].size(); vector<int> res; if(rows == 0 || cols == 0) return res; int left = 0, right = cols-1, up = 0, bottom = rows-1; while(left <= right && up <= bottom){ // 上面一行 for(int i = left; i <= right; i++){ res.push_back(matrix[up][i]); } // 右侧一列 for(int i = up+1; i <= bottom; i++){ res.push_back(matrix[i][right]); } // 下面一行 if(up != bottom){ for(int i = right-1; i >= left; i--){ res.push_back(matrix[bottom][i]); } } // 左侧一列 if(left != right){ for(int i = bottom-1; i > up; i--){ res.push_back(matrix[i][left]); } } left++; right--; up++; bottom--; } return res; } };
|
时间复杂度为O(n^2),空间复杂度为O(n)
以上,本题结束!