| 1 | 2 | 3 | 4 | 5 |
| 16 | 17 | 18 | 19 | 6 |
| 15 | 24 | 25 | 20 | 7 |
| 14 | 23 | 22 | 21 | 8 |
| 13 | 12 | 11 | 10 | 9 |
조금 어려운 문제이긴 하지만, 쉽게 풀 수 있다.
내가 생각해낸 방법은 다음과 같다.
펼쳐두기..
#include <stdio.h>
#define SIZE 5
#define RIGHT 0
#define DOWN 1
#define LEFT 2
#define UP 3
int main()
{
int matrix[SIZE][SIZE] = { { 0 } };
int i, j;
int value;
int direction;
value = 1;
i = j = 0;
direction = 0;
while (value <= SIZE * SIZE) {
matrix[i][j] = value++;
switch (direction) {
case RIGHT:
if (j < SIZE - 1 && matrix[i][j + 1] == 0) {
++j;
} else {
++i;
direction = DOWN;
}
break;
case DOWN:
if (i < SIZE - 1 && matrix[i + 1][j] == 0) {
++i;
} else {
--j;
direction = LEFT;
}
break;
case LEFT:
if (j > 0 && matrix[i][j - 1] == 0) {
--j;
} else {
--i;
direction = UP;
}
break;
case UP:
if (i > 0 && matrix[i - 1][j] == 0) {
--i;
} else {
++j;
direction = RIGHT;
}
break;
}
}
// print result
for (i = 0; i < SIZE; ++i) {
for (j = 0; j < SIZE; ++j) {
printf("%2d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
#define SIZE 5
#define RIGHT 0
#define DOWN 1
#define LEFT 2
#define UP 3
int main()
{
int matrix[SIZE][SIZE] = { { 0 } };
int i, j;
int value;
int direction;
value = 1;
i = j = 0;
direction = 0;
while (value <= SIZE * SIZE) {
matrix[i][j] = value++;
switch (direction) {
case RIGHT:
if (j < SIZE - 1 && matrix[i][j + 1] == 0) {
++j;
} else {
++i;
direction = DOWN;
}
break;
case DOWN:
if (i < SIZE - 1 && matrix[i + 1][j] == 0) {
++i;
} else {
--j;
direction = LEFT;
}
break;
case LEFT:
if (j > 0 && matrix[i][j - 1] == 0) {
--j;
} else {
--i;
direction = UP;
}
break;
case UP:
if (i > 0 && matrix[i - 1][j] == 0) {
--i;
} else {
++j;
direction = RIGHT;
}
break;
}
}
// print result
for (i = 0; i < SIZE; ++i) {
for (j = 0; j < SIZE; ++j) {
printf("%2d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}



