leetcode-剑指29-OK

同主站54
address

/**
 * 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] == 0)){
        returnSize[0] = 0;
        return NULL;
    }
    returnSize[0] = matrixSize*matrixColSize[0];
    int *ans = (int *)malloc(sizeof(int)*returnSize[0]);
    int next = 0;
    void fill(int m){
        ans[next++] = m;
    }
    void round(int up, int down, int left,int right){
        if(up==down){
            for(int i = left;i<=right;i++)
                fill(matrix[up][i]);
        }else if(left==right){
            for(int i = up;i<=down;i++)
                fill(matrix[i][left]);
        }else{
            int i;
            for(i =left; i<=right; i++)
                fill(matrix[up][i]);
            for(i = up+1;i<=down;i++)
                fill(matrix[i][right]);
            for(i = right-1; i>=left;i--)
                fill(matrix[down][i]);
            for(i = down-1;i>up;i--)
                fill(matrix[i][left]);
        }
    }
    int up1=0, down1 =matrixSize-1,left1 = 0, right1 = matrixColSize[0] -1;
    while((down1>=up1)&&(right1>=left1)){
        round(up1,down1,left1,right1);
        up1++;
        down1--;
        left1++;
        right1--;
    }
    return ans;
}
posted @ 2021-01-25 00:18  RougeBW  阅读(38)  评论(0编辑  收藏  举报