Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
题解:还是找规律的题:设有四个变量Xs,Xe,Ys,Ye,如下图所示,它们分别代表当前还未处理的子矩阵的边界,初始为图一所示;运算过程的某一时刻如图二所示
那么螺旋输出就是不停的重复以下四个步骤,直到矩阵所有的元素被输出:
1.输出matrix[Xs->Xe][Ys],Ys++ 即1,2,3
2.输出matrix[Xe][Ys->Ye],Xe-- 即6,9
3.输出matrix[Xe->Xs][Ye],Ye-- 即8,7
4.输出matrix[Ye->Ys][Xs],Xs++ 即4
代码如下:
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 class Solution { 5 public: 6 vector<int> spiralOrder(vector<vector<int> > &matrix) { 7 vector<int> ans; 8 9 if(matrix.size() == 0) 10 return ans; 11 12 int Xs = 0,Xe = matrix[0].size()-1,Ys = 0,Ye = matrix.size()-1; 13 int total = (Xe+1) * (Ye+1); 14 15 for(int i = 0;i <= total;){ 16 for(int k = Xs;k <= Xe;k++) 17 { 18 ans.push_back(matrix[Ys][k]); 19 i++; 20 } 21 if(i >= total) 22 break; 23 else 24 Ys++; 25 26 for(int k = Ys;k <= Ye;k++) 27 { 28 ans.push_back(matrix[k][Xe]); 29 i++; 30 } 31 if(i >= total) 32 break; 33 else 34 Xe--; 35 36 for(int k = Xe;k >= Xs;k--) 37 { 38 ans.push_back(matrix[Ye][k]); 39 i++; 40 } 41 if(i >= total) 42 break; 43 else 44 Ye--; 45 46 for(int k = Ye;k >= Ys;k--) 47 { 48 ans.push_back(matrix[k][Xs]); 49 i++; 50 } 51 if(i >= total) 52 break; 53 else 54 Xs++; 55 } 56 return ans; 57 } 58 }; 59 int main(){ 60 Solution s; 61 vector<vector<int> > m; 62 vector<int>temp(1,1); 63 m.push_back(temp); 64 65 vector<int> ans(s.spiralOrder(m)); 66 cout <<ans.size()<<endl; 67 }
这里学习到了怎么接受函数返回回来的向量,直接定义新的向量初始化为函数返回值就可以了,如代码65行所示。