Leetcode 螺旋数组Ⅱ

编程入门 行业动态 更新时间:2024-10-26 20:29:46

Leetcode 螺旋<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组Ⅱ"/>

Leetcode 螺旋数组Ⅱ

题目描述

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

示例:

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

分析:
从左到右、从上到下、从右到左、从下到上赋值矩阵

思路解析
class Solution:def generateMatrix(self, n: int) -> [[int]]:left, right, top, bottom = 0, n - 1, 0, n - 1matrix = [[0 for _ in range(n)] for _ in range(n)]num, tar = 1, n * nwhile num <= tar:for i in range(left, right + 1): # left to rightmatrix[top][i] = numnum += 1top += 1for i in range(top, bottom + 1): # top to bottommatrix[i][right] = numnum += 1right -= 1for i in range(right, left - 1, -1): # right to leftmatrix[bottom][i] = numnum += 1bottom -= 1for i in range(bottom, top - 1, -1): # bottom to topmatrix[i][left] = numnum += 1left += 1return matrix

更多推荐

Leetcode 螺旋数组Ⅱ

本文发布于:2023-07-28 15:43:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239138.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   螺旋   Leetcode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!