[leetcode] 59. Spiral Matrix II @ python

5915 ワード

原題
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解法
まずn*nの0行列を初期化し、次に右、下、左、上の方向を定義し、n回遍歴し、数字iを行列のある位置に与えるたびに、ここでの位置の決定条件は、次の位置のindexが行列の範囲内であり、次の位置の値が0である場合、私たちは現在の方向に歩いて、さもなくば方向を変えてx,yの値を更新することである.
コード#コード#
class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        res = [[0]*n for _ in range(n)]
        # directions for right, down, left, up
        directions = [(0, 1), (1,0), (0,-1), (-1,0)]
        x, y, d = 0, 0, 0
        for i in range(1, n**2+1):
            res[x][y] = i
            dx, dy = directions[d%4]
            if 0 <= x+dx < n and 0<= y+dy < n and res[x+dx][y+dy] == 0:
                # move according to the current direction
                x, y = x+dx, y+dy
            else:
                # change direction
                d += 1
                dx, dy = directions[d%4]
                x, y = x+dx, y+dy
                
        return res