问题描述:
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].
这道题没啥可说的,上代码:
int* spiralOrder(int** matrix, int matrixRowSize, int matrixColSize) {
int length = matrixRowSize*matrixColSize;
int *result = (int *)malloc(sizeof(int)*length);
char *visited = (char *)calloc(length,sizeof(char));//store visited element
int index = 0;
int row=0,col=-1;
while(1){
if(index == length)
break;
for(col=col+1;col<matrixColSize;col++){
if(visited[row*matrixColSize+col] == 1)
break;
result[index++]=matrix[row][col];
visited[row*matrixColSize+col] = 1;
}
col--;
for(row = row+1;row<matrixRowSize;row++){
if(visited[row*matrixColSize+col] == 1)
break;
result[index++] = matrix[row][col];
visited[row*matrixColSize+col] = 1;
}
row--;
for(col = col-1;col>=0;col--){
if(visited[row*matrixColSize+col] == 1)
break;
result[index++] = matrix[row][col];
visited[row*matrixColSize+col] = 1;
}
col++;
for(row = row-1;row>=0;row--){
if(visited[row*matrixColSize+col] == 1)
break;
result[index++] = matrix[row][col];
visited[row*matrixColSize+col] = 1;
}
row++;
}
return result;
}