59. Spiral Matrix II

網(wǎng)站建設哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、成都微信小程序、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了應城免費建站歡迎大家使用!
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;
}
文章題目:[LeetCode]59.SpiralMatrixII
網(wǎng)站路徑:http://www.chinadenli.net/article4/gpciie.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設、微信公眾號、定制開發(fā)、網(wǎng)站導航、外貿(mào)建站、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)