螺旋矩阵 54/59

lession learn: 判断数据为空时 需要注意不能使用*matrixCokSize, 因为本身就有可能是NULL

正确的方法:

    if (matrix == NULL || matrixSize == 0) {
        *returnSize = 0;
        return NULL;
    }

错误方法:

    if (matrix == NULL || (matrixSize <= 0 && *matrixColSize <= 0)) {
        *returnSize = 0;
        return NULL;
    }

螺旋矩阵 54/59_第1张图片

nt* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
    if (matrix == NULL || matrixSize == 0) {
        *returnSize = 0;
        return NULL;
    }
    int row = matrixSize;
    int col = *matrixColSize;
    int left = 0;
    int right = col - 1;
    int top = 0;
    int botom = row - 1;
    int num = 0;
    int *map = (int *) malloc(row * col * sizeof(int));

    while (1) {
        for(int j = left; j <= right; j++) {
            map[num++] = matrix[top][j];
        }
        if(++top > botom)
            break;
        for (int j = top; j <= botom; j++) { 
            map[num++] = matrix[j][right];
        }

        if(--right < left)
            break;
        for (int j = right; j >= left; j--) {
            map[num++] = matrix[botom][j];
        }
        if(--botom < top)
        break;
        for (int j = botom; j >= top; j--) {
            map[num++] = matrix[j][left];
        }
        if(++left > right)
        break;
    }
    
    *returnSize = row * col;
    return map;
}

螺旋矩阵 54/59_第2张图片

int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
{
    if (n <= 0) {
        *returnSize = 0;
        return NULL;
    }
    int num = 1;
    int left = 0;
    int right = n - 1;
    int top = 0;
    int botom = n - 1;
    int **map = (int **)malloc(n * sizeof(int *));
    for (int i = 0; i < n; i++) {
        map[i] = (int *)malloc(n * sizeof(int));
    }
    while (num <= n * n) {
        for(int j = left; j <= right; j++) {
            map[top][j] = num++;
        }
        top++;
        for (int j = top; j <= botom; j++) { 
            map[j][right] = num++;
        }
        right--;
        for (int j = right; j >= left; j--) {
            map[botom][j] = num++;
        }
        botom--;
        for (int j = botom; j >= top; j--) {
            map[j][left] = num++;
        }
        left++;
    }
    *returnSize = n;
    *returnColumnSizes = (int *) malloc(n *sizeof(int));
    for (int i = 0; i < n; i++) {
        (*returnColumnSizes)[i] = n;
    }
    return map;
}

 

 

 

你可能感兴趣的:(螺旋矩阵 54/59)