主页 > 互联网  > 

leetcode59.螺旋矩阵II中等

leetcode59.螺旋矩阵II中等

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例 1:

输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

输入:n = 1 输出:[[1]]

提示:

1 <= n <= 20

分析:模拟矩阵的生成即可。

/** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) { int **ans=(int**)malloc(sizeof(int*)*(n*n)); for(int i=0;i<n;++i) ans[i]=(int*)malloc(sizeof(int)*n); *returnSize=n; *returnColumnSizes=(int*)malloc(sizeof(int)*n); for(int i=0;i<n;++i) (*returnColumnSizes+i)[0]=n; int cnt=n*n,i=0,j=0,num=1,up,down,left,right; up=down=left=right=0; while(num<=cnt) { while(j<n-right) ans[i][j]=num,num++,j++; j--,right++,i++; while(i<n-up) ans[i][j]=num,num++,i++; i--,down++,j--; while(j>=0+left) ans[i][j]=num,num++,j--; j++,left++,i--; while(i>=0+down) ans[i][j]=num,num++,i--; i++,up++,j++; } return ans; }

标签:

leetcode59.螺旋矩阵II中等由讯客互联互联网栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“leetcode59.螺旋矩阵II中等