题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.*/
class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { int up,down,left,right; vector<int> result; int row = matrix.size(); if(row == 0) return result; int col = matrix[0].size(); up = left = 0; right = col-1; down = row -1; int sig = 1; //right = down = matrix.size()-1; while((up<=down)&&(left<=right)){ if(sig ==1){ for(int i = left;i<=right;i++){ result.push_back(matrix[up][i]); } up++; sig=2; }else if(sig ==2){ for(int j =up;j<=down;j++){ result.push_back(matrix[j][right]); } right--; sig=3; }else if(sig ==3){ for(int i = right;i>=left;i--){ result.push_back(matrix[down][i]); } down--; sig=4; }else if (sig ==4){ for(int j =down;j>=up;j--){ result.push_back(matrix[j][left]); } left++; sig=1; } } if(up<=down){ if(sig==4){ for(int j = down;j>=up;j--){ result.push_back(matrix[j][left]); } }else if(sig ==2){ for(int j =up;j<=down;j++){ result.push_back(matrix[j][right]); } } if(left<=right){ if(sig ==1 ){ for(int i = left;i<=right;i++){ result.push_back(matrix[up][i]); } }else if(sig == 3){ for(int i = right;i>=left;i--){ result.push_back(matrix[down][i]); } } } } return result; } };
时间: 2024-11-08 19:06:52