- 螺旋矩阵 给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
if(matrixSize==0||matrixColSize==0)
return NULL;
*returnSize = matrixSize*(*matrixColSize);
char * in =(char *)malloc(sizeof(char)*(*returnSize));
for(int i =0;i<(*returnSize);i++)
{
in[i]='a';
}
int * res = (int *)malloc(sizeof(int)*(*returnSize));
int direction[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int directionIndex =0;
int col = 0;
int row=0;
for(int i =0;i<(*returnSize);i++)
{
int dd =row*(*matrixColSize)+col;
in[dd] ='b';
printf("行:%d",row);
printf("列:%d",col);
printf("%d\n",dd);
res[i]=matrix[row][col];
int newrow = row+direction[directionIndex][0];
int newcol = col+ direction[directionIndex][1];
int charIndex =newrow*(*matrixColSize)+newcol;
if(newrow<0||newrow>=matrixSize||newcol<0||newcol>=*matrixColSize||in[charIndex]!='a')
{
directionIndex = (directionIndex+1)%4;
}
row = row+direction[directionIndex][0];
col = col+ direction[directionIndex][1];
}
free(in);
return res;
}
找了好久的bug 原来是计算字符数组的下标出错了,以后可要注意了,不要相当然