您的位置:首页 > 其它

[LeetCode]59. Spiral Matrix II

2016-10-05 00:08 387 查看
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 ]
]


题意:
给定一个整数n,生成一个包含1到n*n所有元素的螺旋形矩阵。

1,二维数组的动态空间分配(int **array大小为m*n):
1)首先分配m个的指针单元:
int **array = (int **)malloc( sizeof(int *) * m );
2)接着分配n个字符的单元:
for ( cnt = 0; cnt < n; cnt += 1 )
{
array[cnt] = (int *)malloc( sizeof( int ) * n );
}

注意:
分配指针单元时sizeof的参数是指针。

2,二维数组动态内存的释放:
for ( cnt = 0; cnt < n; cnt += 1 )
{
free( (void *)array[cnt] );
}

free( (void *)array );

3,变量含义:
定义brow代表从左到右执行的次数,erow代表从右到左执行的次数;bcol代表从下往上读取次数,ecol代表从上往下读取次数。所以有:
1)从左往右读取时,必须从bcol列开始读取,递增直到ecol列。
2)从右往左读取时,必须从ecol列开始读取,递减直到bcol列。
2)从上往下读取时,必须从brow行开始读取,递增直到erow行。
4)从下往上读取时,必须从erow行开始读取,递减直到brow行。
其他规则同《[LeetCode]54. Spiral Matrix》

/**
* Return an array of arrays.
* Note: The returned array must be malloced, assume caller calls free().
*/
int** generateMatrix(int n)
{
if ( n <= 0 )
{
return NULL;
}

int **array = (int **)malloc( sizeof( int *) * n  );
if ( !array )
{
return NULL;
}

int cnt = 0;
for ( cnt = 0; cnt < n; cnt += 1 )
{
array[cnt] = (int *)malloc( sizeof( int ) * n );
}

int brow = 0;
int erow = n - 1;
int bcol = 0;
int ecol = n - 1;
int times = 1;
int value = 1;
cnt = 0;
while ( cnt < n * n )
{
if ( times % 4 == 1 )
{
int count = bcol;
while ( count <= ecol )
{
array[brow][count] = value;
count += 1;
value += 1;
}

cnt = cnt + count - bcol;
brow += 1;
}
else if ( times % 4 == 2 )
{
int count = brow;
while ( count <= erow )
{
array[count][ecol] = value;
count += 1;
value += 1;
}

cnt = cnt + count - brow;
ecol -= 1;
}
else if ( times % 4 == 3 )
{
int count = ecol;
while ( count >= bcol )
{
array[erow][count] = value;
count -= 1;
value += 1;
}

cnt = cnt + ecol - count;
erow -= 1;
}
else
{
int count = erow;
while ( count >= brow )
{
array[count][bcol] = value;
count -= 1;
value += 1;
}

cnt = cnt + erow - count;
bcol += 1;
}
times += 1;
}

return array;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode