万事开头难
本题与54题相同,哈哈,学了新思路,舒服多了
新思路体现在重新定义边界,不需要记录已经走过的路径,走完直接扔掉
判断若重新定义后,边界交错,则遍历结束,跳出循环,返回答案。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
if (matrixSize == 0) {
*returnSize = 0;
return NULL;
}
int *ans = (int*)malloc(sizeof(int)*matrixSize*(*matrixColSize));
int top = 0,bottom = matrixSize - 1,left = 0,right = *matrixColSize - 1;
int index = 0;
while(true){
//最上面一层,从左往右
for(int i = left;i <= right;i++){
ans[index++] = matrix[top][i];
}
if(++top > bottom) break;
//右侧从上往下
for(int j = top;j <= bottom;j++)
ans[index++] = matrix[j][right];
if(--right < left) break;
//下侧从右往左
for(int i = right;i >= left;i--)
ans[index++] = matrix[bottom][i];
if(--bottom < top) break;
//左侧从下往上
for(int j = bottom; j>=top;j--)
ans[index++] = matrix[j][left];
if(++left > right) break;
}
*returnSize = *matrixColSize * matrixSize;
return ans;
}