Leetcode 59. Spiral Matrix II

题目

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example, Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

分析

使用上题同样的思路://www.greatytc.com/p/95f8ed55903b
在上题螺旋记录数据的地方改为数组的赋值即可。
这里使用的4个方向的判断中,可以使用循环,直到该方向完成才结束,速度应该更快一点,不过所有的提交代码运行时间都一样。

/**
 * Return an array of arrays.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int** generateMatrix(int n) {
    int **ans=(int **)malloc(sizeof(int *)*n);
    if(n==0)return ans;
    for(int i=0;i<n;i++)
        ans[i]=(int *)malloc(sizeof(int)*n);
    int circle=0;//第几圈
    int p=1;//螺旋旋转方向1->2->3->4->1
    int r=0,c=0;//当前旋转到的位置
    int num=0;
    ans[0][0]=1;
    while(num<n*n)
    {
        //printf("%d %d\n",r,c);
        if(p==1)
        {
            if(c<n-circle-1)
            {
                ans[r][c]=num+1;
                c++;
                num++;
            }
            else
                p=2;
        }
        else if(p==2)
        {
            if(r<n-circle-1)
            {
                ans[r][c]=num+1;
                r++;
                num++;
            }
            else
                p=3;
        }
        else if(p==3)
        {
            if(c>circle)
            {
                ans[r][c]=num+1;
                c--;
                num++;
            }
            else if(c==circle)
            {
                ans[r][c]=num+1;
                r--;
                p=4;
                num++;
            }
        }
        else
        {
            if(r>circle+1)
            {
                ans[r][c]=num+1;
                r--;
                num++;
            }
            else if(r==circle+1)
            {
                ans[r][c]=num+1;
                c++;
                num++;
                p=1;
                circle++;
            }
        }
    }
    return ans;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容