-
Notifications
You must be signed in to change notification settings - Fork 2
/
59. Spiral Matrix II.cpp
81 lines (58 loc) · 1.12 KB
/
59. Spiral Matrix II.cpp
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
/*
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 ]
]
*/
#include<stdio.h>
#include<stdlib.h>
int** generateMatrix(int n) {
int **matrix;
int i,j,k,u,v;
int size,num;
matrix = (int**)malloc(sizeof(int*)*n);
for( i = 0; i < n; i++ ){
*(matrix+i) = (int*)malloc(sizeof(int)*n);
}
size = n*n;
num = 1;
for( i = 0; i < n; i++ ){
for( j = i; j < n - i; j++ ){
matrix[i][j] = num++;
}
j--;
if( num > size ) break;
for( k = i+1; k < n-i; k++ ){
matrix[k][j] = num++;
}
k--;
if( num > size ) break;
for( u = n-2-i; u >= i; u-- ){
matrix[k][u] = num++;
}
u++;
if( num > size ) break;
for( v = n-2-i; v > i; v-- ){
matrix[v][u] = num++;
}
if( num > size ) break;
}
return matrix;
}
int main()
{
int n = 3;
int **matrix = generateMatrix(n);
for( int i = 0; i < n; i++ ){
for( int j = 0; j < n; j++ ){
printf("%d\t",matrix[i][j]);
}
printf("\n");
}
}