Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. class Solution {
  2. public:
  3. vector<int> spiralOrder(vector<vector<int>>& matrix) {
  4. int m=matrix.size();
  5. vector<int> result;
  6. if(m==0)
  7. return result;
  8.  
  9.  
  10. if(m==1)
  11. return matrix.front();
  12. int n=matrix.front().size();
  13.  
  14. int up=0,left=0,down=m,right=n;
  15. int direction=1;
  16. int i=0;
  17. int j=0;
  18. while(up!=down&&left!=right)
  19. {
  20. result.push_back(matrix[i][j]);
  21. if(direction==1)//left
  22. {
  23. if(j+1<right)
  24. {
  25. j++;
  26. }
  27. else
  28. {
  29. up++;
  30. i++;
  31. direction=2;
  32. }
  33. }
  34. else if(direction==2)//down
  35. {
  36. if(i+1<down)
  37. {
  38. ++i;
  39. }
  40. else
  41. {
  42. right--;
  43. --j;
  44. direction=3;
  45. }
  46. }
  47. else if(direction==3)//left
  48. {
  49. if(j>left)
  50. {
  51. --j;
  52. }
  53. else
  54. {
  55. --down;
  56. --i;
  57. direction=0;
  58. }
  59. }
  60. else//up
  61. {
  62. if(i>up)
  63. {
  64. --i;
  65. }
  66. else
  67. {
  68. ++j;
  69. left++;
  70. direction=1;
  71. }
  72. }
  73. }
  74. return result;
  75. }
  76. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement