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; }