The number spiral is a square with a odd-numbered side length, starts with 0 in the middle, and spirals out counterclockwise until there are a total of [the odd number squared] numbers.
Like this:
16 15 14 13 12
17 4 3 2 11
18 5 0 1 10
19 6 7 8 9
20 21 22 23 24
I'm imagining the first value of
array a to be its vertical coordinate, horizontal with the second.
Up is positive [first value of a], right is positive [second value of a].
v and
h is the vertical and horizontal coordinate of where the "next number goes
here pointer thingy" (NNGHPT) goes, respectively.
My approach is to fill the slot of where NNHGPT is with
i, which decreases every time a number is filled, and decide where NNGHPT goes next.
To decide where NNGHPT goes next, it will first decide if the next slot in the direction it is going (dir 1=left, dir 2=up, dir 3=right, dir4= down) is already filled or not in the array, if so, it will turn right(in its perspective), and then move in that direction. If the next slot in the direction it is going is valid, it goes there.
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
|
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int a[n][n]={ },i=n*n-1,v=n-1,h=n-1,dir=1;
while(i>=0)
{
a[v][h]==i;
i--;
if(dir==1)
{
if(h-1<0||a[v][h-1]!=0)
{
dir=2;
v--;
}
else h--;
}
if(dir==2)
{
if(v-1<0||a[v-1][h]!=0)
{
dir=3;
h++;
}
else v--;
}
if(dir==3)
{
if(h+1>n-1||a[v][h+1]!=0)
{
dir=4;
v++;
}
else h++;
}
if(dir==4)
{
if(v+1>n-1||a[v+1][h]!=0)
{
dir=1;
h--;
}
else v++;
}
}
for(int j=0;j<n;j++)
{
for(int k=0;j<n;k++)
cout<<a[j][k];
cout<<endl;
}
}
}
|
Am I over-complicating things again? If so, where and how?
(Programs outputting huge numbers will be the bane of my sanity, ugh.)