Leetcode 54. Spiral Matrix

题目

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

分析

给定一个m*n的矩阵,按照螺旋方向,返回所有的元素,这个比较简单,只需要对行列进行控制,按照螺旋旋转的方向,依次递增或递减行列索引即可。

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* spiralOrder(int** matrix, int matrixRowSize, int matrixColSize) {
    int * ans=(int *)malloc(sizeof(int)*matrixRowSize*matrixColSize);
    int circle=0;//第几圈
    int p=1;//螺旋旋转方向1->2->3->4->1
    int m=0,n=0;//当前旋转到的位置
    int num=0;
    while(numcircle)
            {
                ans[num]=matrix[m][n];
                n--;
                num++;
            }
            else if(n==circle)
            {
                ans[num]=matrix[m][n];
                m--;
                p=4;
                num++;
            }
        }
        else
        {
            if(m>circle+1)
            {
                ans[num]=matrix[m][n];
                m--;
                num++;
            }
            else if(m==circle+1)
            {
                ans[num]=matrix[m][n];
                n++;
                num++;
                p=1;
                circle++;
            }
        }
    }
    return ans;
}

你可能感兴趣的:(Leetcode 54. Spiral Matrix)