#include <iostream>
#include <cmath>
void print_spiral (int ** matrix, int size);
int main()
{
int ** matrix = new int * [4];
for (int i=0; i<4; i++) matrix[i] = new int[4];
// { 7, 8, 9, 10 },
// { 6, 1, 2, 11 },
// { 5, 4, 3, 12 },
// { 16, 15, 14, 13 }
matrix[0][0] = 7; matrix[0][1] = 8; matrix[0][2] = 9; matrix[0][3] = 10;
matrix[1][0] = 6; matrix[1][1] = 1; matrix[1][2] = 2; matrix[1][3] = 11;
matrix[2][0] = 5; matrix[2][1] = 4; matrix[2][2] = 3; matrix[2][3] = 12;
matrix[3][0] = 16; matrix[3][1] = 15; matrix[3][2] = 14; matrix[3][3] = 13;
print_spiral(matrix, 4);
return 0;
}
void print_spiral (int ** matrix, int size)
{
int x = 0; // current position; x
int y = 0; // current position; y
int d = 0; // current direction; 0=RIGHT, 1=DOWN, 2=LEFT, 3=UP
int c = 0; // counter
int s = 1; // chain size
// starting point
x = ((int)floor(size/2.0))-1;
y = ((int)floor(size/2.0))-1;
for (int k=1; k<=(size-1); k++)
{
for (int j=0; j<(k<(size-1)?2:3); j++)
{
for (int i=0; i<s; i++)
{
std::cout << matrix[x][y] << " ";
c++;
switch (d)
{
case 0: y = y + 1; break;
case 1: x = x + 1; break;
case 2: y = y - 1; break;
case 3: x = x - 1; break;
}
}
d = (d+1)%4;
}
s = s + 1;
}
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y21hdGg+Cgp2b2lkIHByaW50X3NwaXJhbCAoaW50ICoqIG1hdHJpeCwgaW50IHNpemUpOwoKaW50IG1haW4oKQp7CglpbnQgKiogbWF0cml4ID0gbmV3IGludCAqIFs0XTsKCWZvciAoaW50IGk9MDsgaTw0OyBpKyspIG1hdHJpeFtpXSA9IG5ldyBpbnRbNF07CgkKCS8vIHsgIDcsICA4LCAgOSwgMTAgfSwKCS8vIHsgIDYsICAxLCAgMiwgMTEgfSwKCS8vIHsgIDUsICA0LCAgMywgMTIgfSwKCS8vIHsgMTYsIDE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k9MDsgaTxzOyBpKyspCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgIHN0ZDo6Y291dCA8PCBtYXRyaXhbeF1beV0gPDwgIiAiOwogICAgICAgICAgICAgICAgYysrOwogICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICBzd2l0Y2ggKGQpCiAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgY2FzZSAwOiB5ID0geSArIDE7IGJyZWFrOwogICAgICAgICAgICAgICAgICAgIGNhc2UgMTogeCA9IHggKyAxOyBicmVhazsKICAgICAgICAgICAgICAgICAgICBjYXNlIDI6IHkgPSB5IC0gMTsgYnJlYWs7CiAgICAgICAgICAgICAgICAgICAgY2FzZSAzOiB4ID0geCAtIDE7IGJyZWFrOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGQgPSAoZCsxKSU0OwogICAgICAgIH0KICAgICAgICBzID0gcyArIDE7CiAgICB9Cn0K