-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffer-29-PrintMatrix.c
128 lines (113 loc) · 2.39 KB
/
offer-29-PrintMatrix.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include "minunit.h"
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int *spiralOrder(int **matrix, int matrixSize, int *matrixColSize, int *returnSize)
{
if (matrixSize == 0 || *matrixColSize == 0)
{
*returnSize = 0;
return NULL;
}
int col = (*matrixColSize), total = matrixSize * col;
int *retVals = (int *)malloc(sizeof(int) * total);
*returnSize = total;
int rowBegin = 0, rowEnd = matrixSize - 1;
int colBegin = 0, colEnd = col - 1;
int index = 0;
while (true)
{
// from left to right
for (int i = colBegin; i <= colEnd; i++)
{
retVals[index++] = matrix[rowBegin][i];
}
rowBegin++;
if (rowBegin > rowEnd)
{
break;
}
// from top to bottom
for (int i = rowBegin; i <= rowEnd; i++)
{
retVals[index++] = matrix[i][colEnd];
}
colEnd--;
if (colEnd < colBegin)
{
break;
}
// from right to left
for (int i = colEnd; i >= colBegin; i--)
{
retVals[index++] = matrix[rowEnd][i];
}
rowEnd--;
if (rowEnd < rowBegin)
{
break;
}
// from bootm to up
for (int i = rowEnd; i >= rowBegin; i--)
{
retVals[index++] = matrix[i][colBegin];
}
colBegin++;
if (colBegin > colEnd)
{
break;
}
}
return retVals;
}
int *spiralOrder1(int **matrix, int matrixSize, int *matrixColSize, int *returnSize)
{
if (matrix == NULL || matrixSize == 0)
{
*returnSize = 0;
return NULL;
}
int m = matrixSize;
int n = matrixColSize[0];
int *ans = malloc(sizeof(int) * m * n);
int count = 0;
int t = 0, b = m - 1, l = 0, r = n - 1;
while (1)
{
for (int i = l; i <= r; i++)
ans[count++] = matrix[t][i]; // from left to right
if (++t > b)
break;
for (int i = t; i <= b; i++)
ans[count++] = matrix[i][r]; // from top to bottom
if (--r < l)
break;
for (int i = r; i >= l; i--)
ans[count++] = matrix[b][i]; // from right to left
if (--b < t)
break;
for (int i = b; i >= t; i--)
ans[count++] = matrix[i][l]; // from bottom to top
if (++l > r)
break;
}
*returnSize = m * n;
return ans;
}
MU_TEST(test_case)
{
mu_check(5 == 7);
}
MU_TEST_SUITE(test_suite)
{
MU_RUN_TEST(test_case);
}
int main()
{
MU_RUN_SUITE(test_suite);
MU_REPORT();
return MU_EXIT_CODE;
}