【leetcode】59. 螺旋矩阵 II

 

int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
    *returnSize=n;
    int** arr=(int**)calloc(n,sizeof(int*));
    *returnColumnSizes=(int*)calloc(n,sizeof(int));
    int up = 0, down = n-1, left = 0, right = n - 1, pst = 0, num=0, i;
    for(i=0; i<n; i++){
        arr[i]=(int*)calloc(n,sizeof(int));
        (*returnColumnSizes)[i]=n;
    }    
    while (num < n*n){
        for (i = left; i <= right && up<=down && left<=right; i++)
            arr[up][i] = ++num;
        up++;
        for (i = up; i <= down && up <= down && left <= right; i++)
            arr[i][right] = ++num;
        right--;
        for (i = right; i >= left && up <= down && left <= right; i--)
            arr[down][i] = ++num;
        down--;
        for (i = down; i >= up && up <= down && left <= right; i--)
            arr[i][left] = ++num;
        left++;
    }
    return arr;
}

 

posted @ 2020-12-11 10:36  温暖了寂寞  阅读(93)  评论(0编辑  收藏  举报