Featured Post

Spiral Matrix In Time Complexity Of O(n)

Hello readers,

Today we are going to discuss the "Spiral Matrix" problem and I will show you how to write a program in python to design the spiral matrix in one loop( O(n) Time Complexity ).

Let's first understand what is a spiral matrix,

This is what a spiral matrix looks like. It's a 2-D, N*N array in which you have to fill the numbers clock wise just in the order shown above.

Note: The size of the array will be taken from the user in our program.

Program:

n=int(input("Enter the size of matrix:"))
arr=[[0 for i in range(0,n)] for j in range(0,n)]
row=0 ; column=0 ; rr=0 ; cc=1
for data in range(1,n*n+1):
         arr[row][column]=data
         next_row=row+rr ; next_column=ccolumn+cc
         if(next_column==n or next_row==n or next_col==-1 or arr[next_row] [next_col]!=0):
                  temp=rr
                  rr=cc
                  cc=-temp
         row=row+rr
         column=column+cc
print("Displaying the matrix:")
for row in range(n):
          for column in range(n):
                  print("%5d"%arr[row][column],end="")
           print("")

Comments