# [leetcode-54]Spiral Matrix(C语言)

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;
}
• 本文已收录于以下专栏：

举报原因： 您举报文章：[leetcode-54]Spiral Matrix(C语言) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)