Print Spiral
#include <stdio.h>
 
void print_spiral(int map[][4])  // need to notify the size ex. map[4][4] or map[][4].    can't use **map 
{
    int i_low, i_high, j_low, j_high, state, i, j;
    i_low = j_low = 0;
    i_high = j_high = 3;
    state = 0;
 
    while (1) {
        switch (state) {     // build a 4 states FSM
            case 0:
                for (i = i_low, j = j_low; i <= i_high; i++)
                    printf("%d ", map[i][j]);
                j_low++;
                break;
            case 1:
                for (i = i_high, j = j_low; j <= j_high; j++)
                    printf("%d ", map[i][j]);
                i_high--;
                break;
            case 2:
                for (i = i_high, j = j_high; i >= i_low; i--)
                    printf("%d ", map[i][j]);
                j_high--;
                break;
            case 3:
                for (i = i_low, j = j_high; j >= j_low; j--)
                    printf("%d ", map[i][j]);
                i_low++;
                break;
        }
        if (i_low > i_high || j_low > j_high)
            return;
        else {
            state = (state + 1) & ~(~0 << 2);               // state (state + 1) % 4
        }
    }
}
 
int main()
{
    int map[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
    print_spiral(map);
}

Output:
1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License