Spiral Matrix--LeetCode

野性酷女 2022-08-05 13:22 18阅读 0赞

题目:

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. [ 1, 2, 3 ],
  3. [ 4, 5, 6 ],
  4. [ 7, 8, 9 ]
  5. ]

You should return [1,2,3,6,9,8,7,4,5].

需要注意下面的一行的答应顺序

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. void SpiralMatrix(vector<vector<int> >& vec)
  5. {
  6. int m=vec.size(); // 行
  7. int n=vec[0].size(); //列
  8. int i,j,tmp,k;
  9. for(i=0;i<(m+1)/2;i++)
  10. {
  11. for(j=i;j<n-i;j++)
  12. cout<<vec[i][j]<<" ";
  13. for(j=j-1,k=i+1;k<m-i;k++)
  14. cout<<vec[k][j]<<" ";
  15. for(k=k-1,j=j-1;k!=i&&j>=i;j--)
  16. cout<<vec[k][j]<<" ";
  17. for(j=k-1;j>i;j--)
  18. cout<<vec[j][i]<<" ";
  19. }
  20. cout<<endl;
  21. }
  22. int main()
  23. {
  24. vector<int> vec(6,0);
  25. vector<vector<int> > image;
  26. int i,j;
  27. for(i=0;i<7;i++)
  28. {
  29. for(j=0;j<vec.size();j++)
  30. vec[j] = i+j+1;
  31. image.push_back(vec);
  32. }
  33. for(i=0;i<image.size();i++)
  34. {
  35. for(j=0;j<vec.size();j++)
  36. cout<<image[i][j]<<" ";
  37. cout<<endl;
  38. }
  39. cout<<"====================="<<endl;
  40. SpiralMatrix(image);
  41. return 0;
  42. }

发表评论

表情:
评论列表 (有 0 条评论,18人围观)

还没有评论,来说两句吧...

相关阅读