Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

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 ] ]

My code:

class Solution:
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        #Init it
        self.max=n**2
        matrix=[]
        for i in range(n):
            tmp_list=[]
            for j in range(n):
                tmp_list.append(0)
            matrix.append(tmp_list)
        self.add_ele(matrix,0,n,0,1)
        return matrix
    def add_ele(self,matrix,i,j,direction,count):
        #print('i %d j %d'%(i,j))
        if count==self.max+1:
            return
        if j-i==1:
            matrix[i][i]=count
            return
        if direction==0:
            for k in range(i,j):
                matrix[i][k]=count
                count+=1
            direction+=1
            self.add_ele(matrix,i,j,direction,count)
        elif direction==1:
            for k in range(i+1,j):
                matrix[k][j-1]=count
                count+=1
            direction+=1
            self.add_ele(matrix,i,j,direction,count)
        elif direction==2:
            for k in range(j-2,i-1,-1):
                matrix[j-1][k]=count
                count+=1
            direction+=1
            self.add_ele(matrix,i,j,direction,count)
        elif direction==3:
            for k in range(j-2,i,-1):
                matrix[k][i]=count
                count+=1
            direction=0
            self.add_ele(matrix,i+1,j-1,direction,count)

Solution: https://leetcode.com/problems/spiral-matrix-ii/