-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path59. Spiral Matrix II.c
94 lines (84 loc) · 2.32 KB
/
59. Spiral Matrix II.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
59. Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
*/
/**
* Return an array of arrays.
* Note: The returned array must be malloced, assume caller calls free().
*/
/**
* Return an array of arrays.
* Note: The returned array must be malloced, assume caller calls free().
*/
int** generateMatrix(int n) {
int left, right, top, bottom;
int i, row, col;
int op = 0;
int **p;
p = malloc(n * sizeof(int *)); // really no such a need to use multiple malloc!!!
//assert(p);
for (i = 0; i < n; i ++) {
p[i] = malloc(n * sizeof(int));
//assert(p[i]);
}
i = 1;
left = 0; right = n;
top = 0; bottom = n;
while (left < right && top < bottom) {
switch (op) {
case 0:
row = top; col = left;
while (col < right) {
p[row][col] = i ++;
col ++;
}
top ++;
break;
case 1:
row = top; col = right - 1;
while (row < bottom) {
p[row][col] = i ++;
row ++;
}
right --;
break;
case 2:
row = bottom - 1; col = right - 1;
while (col >= left) {
p[row][col] = i ++;
col --;
}
bottom --;
break;
case 3:
row = bottom - 1; col = left;
while (row >= top) {
p[row][col] = i ++;
row --;
}
left ++;
break;
}
op = (op + 1) % 4;
}
return p;
}
/*
Difficulty:Medium
Total Accepted:84.2K
Total Submissions:212.5K
Related Topics Array
Similar Questions Spiral Matrix
*/