zoukankan      html  css  js  c++  java
  • [leetcode]Spiral Matrix II @ Python

    原题地址:https://oj.leetcode.com/problems/spiral-matrix-ii/

    题意:

    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    For example,
    Given n = 3,

    You should return the following matrix:
    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]

    解题思路:和上题差不多的思路。

    代码:

    class Solution:
        # @return a list of lists of integer
        def generateMatrix(self, n):
            if n == 0: return []
            matrix = [[0 for i in range(n)] for j in range(n)]
            up = 0; down = len(matrix)-1
            left = 0; right = len(matrix[0])-1
            direct = 0; count = 0
            while True:
                if direct == 0:
                    for i in range(left, right+1):
                        count += 1; matrix[up][i] = count
                    up += 1
                if direct == 1:
                    for i in range(up, down+1):
                        count += 1; matrix[i][right] = count
                    right -= 1
                if direct == 2:
                    for i in range(right, left-1, -1):
                        count += 1; matrix[down][i] = count
                    down -= 1
                if direct == 3:
                    for i in range(down, up-1, -1):
                        count += 1; matrix[i][left] = count
                    left += 1
                if count == n*n: return matrix
                direct = (direct+1) % 4
  • 相关阅读:
    Python编程知识
    Ubuntu 20.04.3 LTS + Intel Realsense 400系列
    Kubectl
    在Debian Buster中安装redis-cli
    MySQL中最近执行的查询的信息
    EntityFramework 在脚本中使用in
    CLDR TimeZone Mapper
    Skyspark Axon
    Async Restsharp call
    HTTP 1.1 中的Accept-Language header
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3769892.html
Copyright © 2011-2022 走看看