aboutsummaryrefslogtreecommitdiff
path: root/Computer_Science/leetcode/59-spiral_matrix_II.c
blob: 27b96bb37a2c2a70cdf6164ae098c64fe2dd6a6f (plain)
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
/**
 * Return an array of arrays.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int** generateMatrix(int n) {
	int **matrix = malloc(sizeof(int *) * n);
	int offset = 0;
	int maxOffset = n / 2 + 1;
	int index = 1;
	int i;

	for(i = 0; i < n; i++)
		*(matrix + i) = malloc(sizeof(int) * n);

	for(offset = 0; offset < maxOffset; offset++, n -= 2) {
		if(n == 0)
			break;
		else if(n == 1) {
			matrix[offset][offset] = index++;
			break;
		} else {
			for(i = 0; i < n; i++)
				matrix[offset][offset + i] = index++;
			for(i = 1; i < n; i++)
				matrix[offset + i][offset + n - 1] = index++;
			for(i = 1; i < n; i++)
				matrix[offset + n - 1][offset + n - 1 - i] = index++;
			for(i = 1; i < n - 1; i++)
				matrix[offset + n - 1 - i][offset] = index++;
		}
	}

	return matrix;
}