マトリックスを時計回りに印刷-レイヤーごとに印刷

マトリックスを時計回りに印刷する

行列を入力し、外側から内側に向​​かって時計回りに各数値を印刷します。

例1:

入力:行列= [[1,2,3]、[4,5,6]、[7,8,9]]
出力:[1,2,3,6,9,8,7,4,5]

例2:

入力:行列= [[1,2,3,4]、[5,6,7,8]、[9,10,11,12]]
出力:[1,2,3,4,8,12、 11,10,9,5,6,7]

制限:

0 <= matrix.length <= 100
0 <= matrix [i] .length <= 100


解決

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
    
    
    // 处理初始化数据
    *returnSize = 0;
    if(matrixSize == 0 || *matrixColSize == 0)
        return 0;
    //真tnn的对简单这俩字有什么误会
    int left = 0,top = 0;
    int bottom = matrixSize - 1, right = *matrixColSize - 1;
    int * p = malloc(sizeof(int)*101*101);
    int * res = p;

    // 按层输出
    // 当在这个范围
    while(left <= right && top <= bottom){
    
    
        // 先一直向右
        // (top, left) -> (top, right)
        int i;
        for(i = left;i <= right;i++){
    
    
            *p = matrix[top][i];
            p++;
            (*returnSize)++;
        }
        if(*returnSize == (*matrixColSize)*matrixSize)
            break;
        // 向下
        // (top+1, right) -> (bottom,right)
        for(i = top+1; i <= bottom; i++){
    
    
            *p = matrix[i][right];
            p++;
            (*returnSize)++;
        }
        if(*returnSize == (*matrixColSize)*matrixSize)
            break;
        // 向左
        // 范围:需要倒序 (left + 1, bottom) -> (right, bottom)
        for(i = right-1;i >= left;i--){
    
    
            *p = matrix[bottom][i];
            p++;
            (*returnSize)++;
        }
        if(*returnSize == (*matrixColSize)*matrixSize)
            break;
        // 向上
        // (bottom,left) -> (top+1, left)
        for(i = bottom-1; i >= top+1; i--){
    
    
            *p = matrix[i][left];
            p++;
            (*returnSize)++;
        }
        if(*returnSize == (*matrixColSize)*matrixSize)
            break;
        // left++;top++;
        // bottom--;right--;
        left++;top++;bottom--;right--;
    }
    return res;
}

おすすめ

転載: blog.csdn.net/qq_39378657/article/details/110426938