Skip to content

Latest commit

 

History

History
24 lines (19 loc) · 785 Bytes

59.-spiral-matrix-ii.md

File metadata and controls

24 lines (19 loc) · 785 Bytes

59. Spiral Matrix II

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

Analysis

We can set the matrix with all zero first. Then we start to walk in the matrix, if the next place is not zero (already visited) or outside the matrix, we turn right.

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        ans=[[0]*n for i in range(n)]
        i,j,stepi,stepj=0,0,0,1
        for k in range(n*n):
            ans[i][j]=k+1
            if i+stepi>=n or j+stepj>=n or ans[i+stepi][j+stepj]!=0:
                stepi,stepj=stepj,-stepi
            i+=stepi
            j+=stepj
        return ans