// g++ -o mat-spiral -std=c++11 mat-spiral.cpp
#include <iostream>
#include <vector>
using namespace std;
using ARRAY = vector<vector<int>>;
const ARRAY m5 {
{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 },
{ 10, 11, 12, 13, 14 },
{ 15, 16, 17, 18, 19 },
{ 20, 21, 22, 23, 24 }
};
const ARRAY m10 {
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
{ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 },
{ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 },
{ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 },
{ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 },
{ 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 },
{ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69 },
{ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79 },
{ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 },
{ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }
};
// N x N matrix spiral
void compute(const ARRAY& mm) {
auto N = mm.size();
cout << "N " << N << endl;
// N of spiral iteration
for (auto i = 0; i < N; i++) {
// top
for (auto j = i; j < N; j++) {
// reach to an end of right column
cout << mm[i][j] << " ";
if (j == N-1) {
cout << endl;
// from top to bottom
for (int k = i+1; k < N; k++)
cout << mm[k][N-1] << " ";
cout << endl;
// from right to left
for (int k = N-2; k >= i; k--)
cout << mm[N-1][k] << " ";
cout << endl;
// from bottom to top
for (int k = N-2; k >= i+1; k--)
cout << mm[k][i] << " ";
cout << endl;
}
}
N--;
}
}
int main() {
compute(m5);
cout << "-----" << endl;
compute(m10);
return 0;
}