50050. Spiral Snake

I'm a slow walker, but I never walk backwards.

Task Description

Write a function SpiralSnake to fill a matrix in a snake-like order.

Suppose we have an $N$ by $N$ grid, $G$ like the following.

p10139. $G\lbrack N]\lbrack N]$

If we go from the center of the matrix and enumerate the elements in clockwise spiral order, we will have a vector of elements like the following.

p10139. $snake\lbrack N^2]$

Now given the snake array, we would like to construct the original matrix $G$, then put the elements back into a result array in a row by row, column by column manner, like the following.

p10139. $result\lbrack N^2]$

The prototype of the function you need to implement is as follows.

1
void SpiralSnake(int N, int *snake, int *result);

The main.c program is as follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include "SpiralSnake.h"
#include <assert.h>
 
#define MAXLEN 1000
 
static int snake[MAXLEN*MAXLEN];
static int result[MAXLEN*MAXLEN];
 
int main(){
    int N;
    while(scanf("%d", &N)!=EOF){
        for(int i=0; i<N*N; i++)
              assert(scanf("%d", &snake[i])==1);
        SpiralSnake(N, snake, result);
        for(int i=0; i<N*N; i++)
             printf("%d%c", result[i], " \n"[i==N*N-1]);
    }
    return 0;
}

The header file SpiralSnake.h is as follows:

1
2
3
4
#ifndef SPIRALSNAKE_H_INCLUDED
#define SPIRALSNAKE_H_INCLUDED
void SpiralSnake(int N, int *snake, int *result);
#endif

Input Format

Input contains multiple test cases, each test case has 2 lines.

The first line in a test case contains one integer, $N$, meaning the matrix size is $N$ by $N$. Then next line contains $N^2$ integers indicating the elements of the snake.

Technical limitation

  • $N$ is odd and $1 \le N \le 999$

Output Format

Print out the result.

Sample Input

3
1 2 3 4 5 6 7 8 9
3
6 8 10 9 16 15 18 23 29

Sample Output

3 4 5 2 1 6 9 8 7
10 9 16 8 6 15 29 23 18

Note

You can use Ctrl+Z (in Windows) or Ctrl+D (in Linux) to input the end-of-file (EOF) character.

Compile

gcc -std=c99 -O2 -c main.c -lm
gcc -std=c99 -O2 -c SpiralSnake.c -lm
gcc -std=c99 -O2 SpiralSnake.o main.o -lm

Discussion