NYUer | LeetCode59 Spiral Matrix II

LeetCode59 Spiral Matrix II


Author: Stefan Su
Create time: 2022-10-27 00:07:21
Location: New York City, NY, USA

Description Medium

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

Example 1

在这里插入图片描述

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2
Input: n = 1
Output: [[1]]
Constrains
  • 1 <= n <= 20

Analysis

Make sure the range of assignment operation at each side of square is consistent. For example, for the topmost side, follow [left, right), and for the rightmost side, follow that rule as well. In this way, we can avoid re-assignment or missing. This is a Simulation problem.

Solution

  • Version 1
class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        nums = [[0] * n for _ in range(n)]
        startx, starty = 0, 0
        loop, mid = n // 2, n // 2
        count = 1

        for offset in range(1, loop + 1):
            for i in range(starty, n - offset):
                nums[startx][i] = count
                count += 1
            for i in range(startx, n - offset):
                nums[i][n - offset] = count
                count += 1
            for i in range(n - offset, starty, -1):
                nums[n - offset][i] = count
                count += 1
            for i in range(n - offset, startx, -1):
                nums[i][starty] = count
                count += 1                
            startx += 1
            starty += 1

        if n % 2 != 0:
            nums[mid][mid] = count 
        return nums

Hopefully, this blog can inspire you when solving LeetCode59. For any questions, please comment below.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值