zoukankan      html  css  js  c++  java
  • 每日一题力扣58 真讨厌螺旋矩阵!

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

    正解:

    class Solution:
        def generateMatrix(self, n: int) -> [[int]]:
            l, r, t, b = 0, n - 1, 0, n - 1 #左边界,右边界,上边界,下边界
            mat = [[0 for _ in range(n)] for _ in range(n)]
            num, tar = 1, n * n
            while num <= tar:
                for i in range(l, r + 1):#从0遍历到右边界
                    mat[t][i] = num#向右走赋值
                    num += 1
                t += 1#下一行
                for i in range(t, b + 1):#从上边界到下边界,
                    mat[i][r] = num
                    num += 1
                r -= 1
                for i in range(r, l - 1, -1):#从右边界到左边界,
                    mat[b][i] = num
                    num += 1
                b -= 1
                for i in range(b, t - 1, -1):
                    mat[i][l] = num
                    num += 1
                l += 1
            return mat
  • 相关阅读:
    模板
    2019牛客暑期多校训练营(第五场)
    Codeforces
    Codeforces
    SCUT
    模板
    Codeforces
    2019 Multi-University Training Contest 4
    Codeforces
    Codeforces
  • 原文地址:https://www.cnblogs.com/liuxiangyan/p/14470811.html
Copyright © 2011-2022 走看看