creating a spiral array in python?

前端 未结 8 652
感情败类
感情败类 2020-12-05 03:16

Me and my mate were trying to create a fun game in python where the elements entered in the array are accessed in a spiral manner. I have tried few methods like one given be

8条回答
  •  猫巷女王i
    2020-12-05 03:50

    def spiral(m):
     a=[]
     t=list(zip(*m)) # you get the columns by zip function
    
     while m!=[]:
      if m==[]:
        break
      m=list(zip(*t)) # zip t will give you same m matrix. It is necessary for iteration
      a.extend(m.pop(0)) # Step1 : pop first row
      if m==[]:
        break
      t=list(zip(*m))
      a.extend(t.pop(-1)) # Step 2: pop last column
      if m==[]:
        break
      m=list(zip(*t))
      a.extend(m.pop(-1)[::-1]) # Step 3: pop last row in reverse order
      if m==[]:
        break
      t=list(zip(*m)) 
      a.extend(t.pop(0)[::-1]) # Step 4: pop first column in reverse order
     return a
    

    This solution is O(n); just one while loop; much faster and can be used for much bigger dimensions of matrices

提交回复
热议问题