-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp059.c
74 lines (74 loc) · 1.49 KB
/
p059.c
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Return an array of arrays.
* Note: The returned array must be malloced, assume caller calls free().
*/
int** generateMatrix(int n) {
if (!n) return NULL;
int **result = (int**)malloc(sizeof(int*)*n);
int i;
int right = n-1, left = 0, down = n-1, up = 1;
int dir = 0;
int x = 0, y = 0;
for (i = 0; i < n; i++)
{
result[i] = (int*)malloc(sizeof(int)*n);
}
int size = n*n;
for (i = 1; i <= size; i++)
{
result[x][y] = i;
if (dir == 0)
{
if (y == right)
{
x++;
dir = 1;
right--;
}
else
{
y++;
}
}
else if (dir == 1)
{
if (x == down)
{
y--;
dir = 2;
down--;
}
else
{
x++;
}
}
else if (dir == 2)
{
if (y == left)
{
x--;
dir = 3;
left++;
}
else
{
y--;
}
}
else
{
if (x == up)
{
y++;
dir = 0;
up++;
}
else
{
x--;
}
}
}
return result;
}