my python solution which is easy to understand but it's not elegant


  • 0
    H
    class Solution(object):
        def generateMatrix(self, n):
            if n==0:
                return []
            i=0
            ans=[([0] * n) for i in range(n)]
            g=1
            ans[0][0]=g
            g+=1
            s=1
            i=0
            j=1
            while(g<=n*n):
                if s==1:
                    if j==n or ans[i][j]!=0:
                        j-=1
                        i+=1
                        s=2
                        continue
                    ans[i][j]=g
                    g+=1
                    j+=1
                if s==2:
                    if i==n or ans[i][j]!=0:
                        i-=1
                        j-=1
                        s=3
                        continue
                    ans[i][j]=g
                    g+=1
                    i+=1
                if s==3:
                    if j==-1 or ans[i][j]!=0:
                        j+=1
                        i-=1
                        s=4
                        continue
                    ans[i][j]=g
                    g+=1
                    j-=1
                if s==4:
                    if ans[i][j]!=0:
                        i+=1
                        j+=1
                        s=1
                        continue
                    ans[i][j]=g
                    g+=1
                    i-=1
            return ans
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.