Solution Idea

50050. Spiral Snake

參考解答

對於Spiral Order可以先運用如下圖的解析:

p50050. Sol'n$

再了解蛇的大致構造後,我們將方向分為0(左)、1(上)、2(右)、3(下),如此一來便能依照+ & %即可控制方向。因為同個位移量需重複兩次,所以再運用一些counter和flag方便控制。

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
#include "SpiralSnake.h"
#include <stdio.h>
 
#define MAXLEN 1000
int A[MAXLEN][MAXLEN];
int dirXY[2][4] = { 0, -1, 0, 1,
                    -1, 0, 1, 0};
 
void SpiralSnake(int N, int *snake, int *result){
    int x, y;
    int dir = 0, flag = 0;
    int changeCount = 1, tmpCC = 1;
    x = y = N/2;
    result[x*N + y] = snake[0];
    for(int i=1; i< N*N; i++){
        x += dirXY[0][dir];
        y += dirXY[1][dir];
        result[x*N + y] = snake[i];
        tmpCC--;
        if(tmpCC == 0){
            dir = (dir + 1) % 4;
            if(flag==0)
                tmpCC = changeCount, flag++;
            else
                tmpCC = ++changeCount, flag = 0;
        }
    }
    return;
}

Discussion