Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Spiral Matrix
Description Title: Given a matrix of mxn elements (m row, n-column) comprising, follow a helical clockwise order, returns all the elements in the matrix.
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
Problem-solving ideas: hierarchical traversal operations from the outside in, the definition of the four directions, pay attention to border operation, this problem needs to do a few times, completely understood. Traversed in the FIG.
- For each layer, from the upper left in clockwise order through all the elements, assumed that the current layer is the top-left corner coordinates {(r1, c1)} (r1, c1), the lower right corner coordinates {(r2, c2)} ( r2, c2).
- First, through all the elements above {(r1, c)} (r1, c), according to {c = c1, ..., c2} c = c1, ..., the order of c2. Then traversing all the elements to the right of {(r, c2)} (r, c2), according {r = r1 + 1, ..., r2} r = r1 + 1, ..., r2 of the order. If this layer has four sides (i.e., {r1 <r2} r1 <r2 and {c1 <c2} c1 <c2), the following embodiment shown in FIG we traverse the elements of the left and below the element.
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
int r,c,r1,r2,c1,c2,count;
if(!matrixSize||!matrixColSize[0]){
*returnSize=0;
return NULL;
}
int *result=(int *)malloc(sizeof(int)*matrixSize*matrixColSize[0]);
*returnSize=matrixSize*matrixColSize[0];
r1=c1=count=0;
r2=matrixSize-1;
c2=matrixColSize[0]-1;
while(r1<=r2&&c1<=c2){
for(c=c1;c<=c2;c++)result[count++]=matrix[r1][c];
for(r=r1+1;r<=r2;r++)result[count++]=matrix[r][c2];
if(r1<r2&&c1<c2){
for(c=c2-1;c>c1;c--)result[count++]=matrix[r2][c];
for(r=r2;r>r1;r--)result[count++]=matrix[r][c1];
}
r1++;
r2--;
c1++;
c2--;
}
return result;
}