54. Spiral Matrix

Given a matrix ofmxnelements (mrows,ncolumns), 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].


题意:

根据给定的m*n矩阵。返回螺旋排序后的一维数组。

123456789螺旋排序后的结果为:1,2,3,6,9,8,7,4,5由此可知读取共分四个方向,而且是四个方向的轮回:1)从左到右(横坐标不变,纵坐标逐步加一)。读取结果为:1232)从上到下(纵坐标不变,横坐标逐步加matrixColSize)。读取结果为:693)从右往左(横坐标不变,纵坐标逐步减一)读取结果为:874)从下往上(纵坐标不变,横坐标逐步减matrixColSize)。读取结果为:4定义brow代表从左到右执行的次数,erow代表从右到左执行的次数;bcol代表从下往上读取次数,ecol代表从上往下读取次数。所以有:1)从左往右读取时,必须从bcol列开始读取,递增直到ecol列。2)从右往左读取时,必须从ecol列开始读取,递减直到bcol列。2)从上往下读取时,必须从brow行开始读取,递增直到erow行。4)从下往上读取时,必须从erow行开始读取,递减直到brow行。



/***Note:Thereturnedarraymustbemalloced,assumecallercallsfree().*/int*spiralOrder(int**matrix,intmatrixRowSize,intmatrixColSize){if(!matrix){returnNULL;}int*dest=(int*)malloc(sizeof(int)*matrixRowSize*matrixColSize+1);if(!dest){returnNULL;}inttimes=1;intnumbers=0;intbrow=0;interow=matrixRowSize-1;intbcol=0;intecol=matrixColSize-1;intindex=0;while(numbers<matrixRowSize*matrixColSize){if(times%4==1){intcount=bcol;while(count<=ecol){*(dest+index)=matrix[brow][count];count++;index++;}numbers=numbers+count-bcol;brow+=1;}elseif(times%4==2){intcount=brow;while(count<=erow){*(dest+index)=matrix[count][ecol];count+=1;index++;}numbers=numbers+count-brow;ecol-=1;}elseif(times%4==3){intcount=ecol;while(count>=bcol){*(dest+index)=matrix[erow][count];count-=1;index++;}numbers=numbers+ecol-count;erow-=1;}else{intcount=erow;while(count>=brow){*(dest+index)=matrix[count][bcol];count-=1;index++;}numbers=numbers+erow-count;bcol+=1;}times+=1;}*(dest+index)='\0';returndest;}