题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
例如,如果输入如下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.
思路
定下3个点,则做四次循环
1、start -> endX
2、start+1 -> endY
3、endY-1 -> start
4、endY -> start - 1
取x为cols,rows中较小的,每做4次循环,x = x - 2
当 x > 0,循环才进行
start | . | . | . | endX |
. | . | . | ||
. | . | . | ||
. | . | . | ||
. | . | . | endY |
class Solution {public: vector printMatrix(vector> matrix) { vector res; int row=matrix.size();//行数 int col=matrix[0].size();//列数 int x = min(row, col), start = 0; while ( x > 0){ int endX = col - 1 - start; int endY = row - 1 - start; for (int i = start; i <= endX; i++) res.push_back(matrix[start][i]); if( start < endY){ for (int i = start +1 ; i <= endY; i++) res.push_back(matrix[i][endX]); } if (start < endX && start < endY){ for (int i = endX - 1; i >= start; i--) res.push_back(matrix[endY][i]); } if (start < endX && start < endY - 1){ for (int i =endY - 1; i > start; i--) res.push_back(matrix[i][start]); } x = x - 2; start++; } return res; }};