您好,登錄后才能下訂單哦!
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 ] ]
題意:
給定一個整數(shù)n,生成一個包含1到n*n所有元素的螺旋形矩陣。
1,二維數(shù)組的動態(tài)空間分配(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的參數(shù)是指針。 2,二維數(shù)組動態(tài)內(nèi)存的釋放: for ( cnt = 0; cnt < n; cnt += 1 ) { free( (void *)array[cnt] ); } free( (void *)array ); 3,變量含義: 定義brow代表從左到右執(zhí)行的次數(shù),erow代表從右到左執(zhí)行的次數(shù);bcol代表從下往上讀取次數(shù),ecol代表從上往下讀取次數(shù)。所以有: 1)從左往右讀取時,必須從bcol列開始讀取,遞增直到ecol列。 2)從右往左讀取時,必須從ecol列開始讀取,遞減直到bcol列。 2)從上往下讀取時,必須從brow行開始讀取,遞增直到erow行。 4)從下往上讀取時,必須從erow行開始讀取,遞減直到brow行。
其他規(guī)則同《[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; }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。