LeetCode:59. Spiral Matrix II 螺旋矩阵 II(C语言)

ゝ一世哀愁。 2023-07-05 10:21 210阅读 0赞

题目描述:
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:

  1. /** * 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(). */
  2. int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
  3. {
  4. *returnSize = n;//返回行数
  5. int **ret = (int**)malloc(sizeof(int*)*n);
  6. int i = 0;
  7. int j = 0;
  8. int count = 1;
  9. int left = 0;
  10. int right = n-1;
  11. int top = 0;
  12. int down = n-1;
  13. for(i = 0;i<n;i++)
  14. {
  15. ret[i] = (int*)malloc(sizeof(int)*n);
  16. }
  17. while(left < right)
  18. {
  19. for(j = left;j<=right;j++)
  20. {
  21. ret[top][j] = count;
  22. count++;
  23. }
  24. top++;
  25. for(i = top;i<=down;i++)
  26. {
  27. ret[i][right] = count;
  28. count++;
  29. }
  30. right--;
  31. for(j = right;j>=left;j--)
  32. {
  33. ret[down][j] = count;
  34. count++;
  35. }
  36. down--;
  37. for(i = down;i>=top;i--)
  38. {
  39. ret[i][left] = count;
  40. count++;
  41. }
  42. left++;
  43. }
  44. if(left == right)
  45. {
  46. ret[top][left] = count;
  47. }
  48. *returnColumnSizes = malloc(sizeof(void*)*n);
  49. for(i = 0;i<n;i++)
  50. {
  51. (*returnColumnSizes)[i] = n;//返回的每行的长度
  52. }
  53. return ret;
  54. }

运行结果:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,210人围观)

还没有评论,来说两句吧...

相关阅读