Print matrix clockwise-print layer by layer

Print matrix clockwise

Enter a matrix and print out each number in clockwise order from the outside to the inside.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12, 11,10,9,5,6,7]

limit:

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


solution

/**
 * 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;
}

Guess you like

Origin blog.csdn.net/qq_39378657/article/details/110426938