Leetcode 54:螺旋矩阵I
整体思路是按题目要求模拟,顺时针转,先从左到右,再从上到下 最后从右到左,从下到上,注意点在于边界值控制
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 35 36 37 38 39 40 41 42 class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) { return {}; } int m = matrix.size(); int n = matrix[0].size(); int up = 0,left = 0; int down = m-1,right = n-1; ventor<int> res; while(up<=down && left<=right) { for(int i = left;i <= right;i++) // 注意<= [left,right] { res.push_back(matrix[up][i]); } for(int i = up + 1;i <= down;i++) //注意+1 <= (up,down] { res.push_back(matrix[i][right]); } if(up<down && left<right) //当up==down的时候我们实际上只有一行要输出,上面已经输出了 { for(int i = right - 1;i > left;i--) //[right,left) { res.push_back(matrix[down][i]); } for(int i = down;i > up;i--) //(down,up) { res.push_back(matrix[i][left]); } } } return res; } };