新聞中心
54. Spiral Matrix

張家口ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為成都創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
題意:
根據(jù)給定的m*n矩陣。返回螺旋排序后的一維數(shù)組。
1 2 3 4 5 6 7 8 9 螺旋排序后的結(jié)果為:1,2,3,6,9,8,7,4,5 由此可知讀取共分四個方向,而且是四個方向的輪回: 1)從左到右(橫坐標(biāo)不變,縱坐標(biāo)逐步加一)。讀取結(jié)果為:1 2 3 2)從上到下(縱坐標(biāo)不變,橫坐標(biāo)逐步加matrixColSize)。讀取結(jié)果為:6 9 3)從右往左(橫坐標(biāo)不變,縱坐標(biāo)逐步減一)讀取結(jié)果為:8 7 4)從下往上(縱坐標(biāo)不變,橫坐標(biāo)逐步減matrixColSize)。讀取結(jié)果為:4 定義brow代表從左到右執(zhí)行的次數(shù),erow代表從右到左執(zhí)行的次數(shù);bcol代表從下往上讀取次數(shù),ecol代表從上往下讀取次數(shù)。所以有: 1)從左往右讀取時,必須從bcol列開始讀取,遞增直到ecol列。 2)從右往左讀取時,必須從ecol列開始讀取,遞減直到bcol列。 2)從上往下讀取時,必須從brow行開始讀取,遞增直到erow行。 4)從下往上讀取時,必須從erow行開始讀取,遞減直到brow行。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* spiralOrder(int** matrix, int matrixRowSize, int matrixColSize)
{
if ( !matrix )
{
return NULL;
}
int *dest = ( int *)malloc( sizeof(int) * matrixRowSize * matrixColSize + 1 );
if ( !dest )
{
return NULL;
}
int times = 1;
int numbers = 0;
int brow = 0;
int erow = matrixRowSize - 1;
int bcol = 0;
int ecol = matrixColSize - 1;
int index = 0;
while ( numbers < matrixRowSize * matrixColSize )
{
if ( times % 4 == 1 )
{
int count = bcol;
while ( count <= ecol )
{
*( dest + index ) = matrix[brow][count];
count++;
index++;
}
numbers = numbers + count - bcol;
brow += 1;
}
else if ( times % 4 == 2 )
{
int count = brow;
while ( count <= erow )
{
*( dest + index ) = matrix[count][ecol];
count += 1;
index++;
}
numbers = numbers + count - brow;
ecol -= 1;
}
else if ( times % 4 == 3 )
{
int count = ecol;
while ( count >= bcol )
{
*( dest + index ) = matrix[erow][count];
count -= 1;
index++;
}
numbers = numbers + ecol - count;
erow -= 1;
}
else
{
int count = erow;
while ( count >= brow )
{
*( dest + index ) = matrix[count][bcol];
count -= 1;
index++;
}
numbers = numbers + erow - count;
bcol += 1;
}
times += 1;
}
*( dest + index ) = '\0';
return dest;
}文章名稱:[LeetCode]54.SpiralMatrix
本文來源:http://m.biofuelwatch.net/article/jccdcs.html


咨詢
建站咨詢
