#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int i=0,x,y,spiral[100][100];
char direction = 'r';
void change_direction() {
switch(direction) {
case 'r':direction='d';break;
case 'd':direction='l';break;
case 'l':direction='u';break;
case 'u':direction='r';break;
}
}
int check_cell(int a,int b) {
if (b >= y || b <0) { return 0; }
else if (a >= x) { return 0; }
else if (spiral[a][b] != 0) { return 0; }
else { return 1; }
}
void move_cell(int &a,int &b) {
int next_a = a, next_b = b;
if (i == x*y-1) { return; }
switch(direction) {
case 'r': next_b = b + 1;break;
case 'd': next_a = a + 1;break;
case 'l': next_b = b - 1;break;
case 'u': next_a = a - 1;break;
}
if (check_cell(next_a,next_b)) {
a = next_a;b = next_b;
}
else {
change_direction();
move_cell(a,b);
}
return;
}
int main() {
int j,a=0,b=0;
srand((unsigned)time(0));
while (!x||!y) { x = rand()%10; y = rand()%10; }
printf("%dx%d spiral number\n",x,y);
for (i = 0;i<x*y;i++) {
spiral[a][b]=i+1;
move_cell(a,b);
}
for (i = 0;i < x;i++) {
for (j = 0;j < y;j++) {
printf("%d\t",spiral[i][j]);
}
printf("\n");
}
return 0;
}