Description
For a given number n, You need to print the spiral matrix of n * n.
For example, if n = 3, the output is:
1 2 3
8 9 4
7 6 5
Input
Multiple groups of test data, each of which contains an integer n (1 <=n <= 32)
Output
For each group of test data, an n * n spiral matrix is output, which is defined in the topic description.
In a set of test data, the character width of each number is the maximum digit plus 1 in the set of data, for example, the spiral matrix of 3*3. The maximum value is 9, then each number occupies 2 Characters in width.
Two groups of test data are separated by one empty row.
Sample Input
1
2
3
Sample Output
1
1 2
4 3
1 2 3
8 9 4
7 6 5
The Code is as follows ~~~)
#include
#include
#include
#include
#define MAXN 105#define RST(N)memset(N, 0, sizeof(N))using namespace std;int Kesha[105][105], cas = 0, n;int main(){ while(~scanf(%d, &n)) { if(cas++) printf(); int x, y, ans = 0; RST(Kesha); ans = Kesha[x=0][y=0] = 1; while(ans < n * n) { while(y + 1 < n && !Kesha[x][y+1]) Kesha[x][++y] = ++ans; while(x + 1 < n && !Kesha[x+1][y]) Kesha[++x][y] = ++ans; while(y - 1 >= 0 && !Kesha[x][y-1]) Kesha[x][--y] = ++ans; while(x - 1 >= 0 && !Kesha[x-1][y]) Kesha[--x][y] = ++ans; } int t = n * n; for(int i=0; i
=10 && t<=99) printf(%3d, Kesha[i][j]); else if(t>=100 && t<=999) printf(%4d, Kesha[i][j]); else if(t >= 1000 ) printf(%5d, Kesha[i][j]); } printf(); } } return 0;}