Leetcode 59. 螺旋矩阵 II (每日一题 20210926)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 59. 螺旋矩阵 II (每日一题 20210926)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個正整數?n ,生成一個包含 1 到?n2?所有元素,且元素按順時針順序螺旋排列的?n x n 正方形矩陣 matrix 。示例 1:輸入:n = 3
輸出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:輸入:n = 1
輸出:[[1]]鏈接:https://leetcode-cn.com/problems/spiral-matrix-iiclass Solution:def generateMatrix(self, n: int) -> List[List[int]]:left, right, top, bottom = 0, n-1, 0, n-1num, target = 1, n * nmat = [[0 for _ in range(n)] for _ in range(n)]while num <= target:for i in range(left, right + 1):mat[top][i] = numnum += 1top += 1for i in range(top, bottom + 1):mat[i][right] = numnum += 1right -= 1for i in range(right, left-1, -1):mat[bottom][i] = numnum += 1bottom -= 1for i in range(bottom, top-1, -1):mat[i][left] = numnum += 1left += 1return mat
總結
以上是生活随笔為你收集整理的Leetcode 59. 螺旋矩阵 II (每日一题 20210926)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 103. 二叉树的锯齿
- 下一篇: Leetcode 120. 三角形最小路