#include <bits/stdc++.h>
using namespace std;
vector<int> printSpiral(vector<vector<int>> mat) {
// Define ans array to store the result.
vector<int> ans;
int n = mat.size(); // no. of nows
int m = mat[0].size(); // no. of columns
// Initialize the pointers reqd for traversal.
int top = 0, left = 0, bottom = n - 1, right = m - 1;
// Loop until all elements are not traversed.
while (top <= bottom && left <= right) {
// For moving left to right
for (int i = left; i <= right; i++)
ans.push_back(mat[top][i]);
top++;
// For moving top to bottom.
for (int i = top; i <= bottom; i++)
ans.push_back(mat[i][right]);
right--;
// For moving right to left.
if (top <= bottom) {
for (int i = right; i >= left; i--)
ans.push_back(mat[bottom][i]);
bottom--;
}
// For moving bottom to top.
if (left <= right) {
for (int i = bottom; i >= top; i--)
ans.push_back(mat[i][left]);
left++;
}
}
return ans;
}
int main() {
//Matrix initialization.
vector<vector<int>> mat {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
vector<int> ans = printSpiral(mat);
for(int i = 0;i<ans.size();i++){
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+Cgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKdmVjdG9yPGludD4gcHJpbnRTcGlyYWwodmVjdG9yPHZlY3RvcjxpbnQ+PiBtYXQpIHsKIAogIC8vIERlZmluZSBhbnMgYXJyYXkgdG8gc3RvcmUgdGhlIHJlc3VsdC4KICB2ZWN0b3I8aW50PiBhbnM7CiAKICBpbnQgbiA9IG1hdC5zaXplKCk7IC8vIG5vLiBvZiBub3dzCiAgaW50IG0gPSBtYXRbMF0uc2l6ZSgpOyAvLyBuby4gb2YgY29sdW1ucwogIAogIC8vIEluaXRpYWxpemUgdGhlIHBvaW50ZXJzIHJlcWQgZm9yIHRyYXZlcnNhbC4KICBpbnQgdG9wID0gMCwgbGVmdCA9IDAsIGJvdHRvbSA9IG4gLSAxLCByaWdodCA9IG0gLSAxOwoKICAvLyBMb29wIHVudGlsIGF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MTJ9LAoJCSAgICAgICAgICAgICAgICAgICAgIHsxMywgMTQsIDE1LCAxNn19OwoJCSAgICAgICAgICAgICAgICAgICAgIAogIHZlY3RvcjxpbnQ+IGFucyA9IHByaW50U3BpcmFsKG1hdCk7CgogIGZvcihpbnQgaSA9IDA7aTxhbnMuc2l6ZSgpO2krKyl7CiAgICAgIAogICAgICBjb3V0PDxhbnNbaV08PCIgIjsKICB9CiAgCiAgY291dDw8ZW5kbDsKICAKICByZXR1cm4gMDsKfQ==