美文网首页
Leetcode 54. Spiral Matrix

Leetcode 54. Spiral Matrix

作者: persistent100 | 来源:发表于2017-06-11 17:31 被阅读0次

    题目

    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(num<matrixRowSize*matrixColSize)
        {
            //printf("%d ",matrix[m][n]);
            if(p==1)
            {
                if(n<matrixColSize-circle-1)
                {
                    ans[num]=matrix[m][n];
                    n++;
                    num++;
                }
                else
                    p=2;
            }
            else if(p==2)
            {
                if(m<matrixRowSize-circle-1)
                {
                    ans[num]=matrix[m][n];
                    m++;
                    num++;
                }
                else
                    p=3;
            }
            else if(p==3)
            {
                if(n>circle)
                {
                    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

          本文链接:https://www.haomeiwen.com/subject/usnhqxtx.html