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.