fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<int> printSpiral(vector<vector<int>> mat) {
  6.  
  7. // Define ans array to store the result.
  8. vector<int> ans;
  9.  
  10. int n = mat.size(); // no. of nows
  11. int m = mat[0].size(); // no. of columns
  12.  
  13. // Initialize the pointers reqd for traversal.
  14. int top = 0, left = 0, bottom = n - 1, right = m - 1;
  15.  
  16. // Loop until all elements are not traversed.
  17. while (top <= bottom && left <= right) {
  18.  
  19. // For moving left to right
  20. for (int i = left; i <= right; i++)
  21. ans.push_back(mat[top][i]);
  22.  
  23. top++;
  24.  
  25. // For moving top to bottom.
  26. for (int i = top; i <= bottom; i++)
  27. ans.push_back(mat[i][right]);
  28.  
  29. right--;
  30.  
  31. // For moving right to left.
  32. if (top <= bottom) {
  33. for (int i = right; i >= left; i--)
  34. ans.push_back(mat[bottom][i]);
  35.  
  36. bottom--;
  37. }
  38.  
  39. // For moving bottom to top.
  40. if (left <= right) {
  41. for (int i = bottom; i >= top; i--)
  42. ans.push_back(mat[i][left]);
  43.  
  44. left++;
  45. }
  46. }
  47. return ans;
  48. }
  49.  
  50. int main() {
  51.  
  52. //Matrix initialization.
  53. vector<vector<int>> mat {{1, 2, 3, 4},
  54. {5, 6, 7, 8},
  55. {9, 10, 11, 12},
  56. {13, 14, 15, 16}};
  57.  
  58. vector<int> ans = printSpiral(mat);
  59.  
  60. for(int i = 0;i<ans.size();i++){
  61.  
  62. cout<<ans[i]<<" ";
  63. }
  64.  
  65. cout<<endl;
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10