How to Extract Matrix Elements in the Spiral Form in Python3?

CLOCKWISE SPIRAL FORM EXTRACTION OF MATRIX ELEMENTS

Clockwise Spiral Form can be best described as:

  • Let’s consider a matrix of m x n dimension, where m is the number of rows and n is the number of columns.
  • Let’s take a point, the point starts from the first element (1,1).
  • Then the point will move in the right direction until the end (1,n).
  • From there, the point will move downwards until the last element of the matrix (m,n).
  • Then, the point move towards the second column (2,n), it will not hit the first column.
  • From there it will rise up to the second row (2,2), it will not touch the first row.
  • This process continues until it covers all the elements.

Read more here: Spiral array model

The Clockwise Spiral Form is shown below in the image.

Spiral Matrix Python

Spiral Matrix Python

Now, let’s take a look at the code snippet

PROGRAM to Extract Matrix Elements in the Spiral Form in Python3 :

# Python3 program to print the given matrix in spiral form 
def spiralPrint(m,n,a): 
    k=0;l=0
    ''' k - starting row index 
        m - ending row index 
        l - starting column index 
        n - ending column index 
        i - iterator '''
    while(k<m and l<n):
        # Print the first row from 
        # the remaining rows  
        for i in range(l,n) : 
            print(a[k][i],end=" ")
        k += 1
        # Print the last column from 
        # the remaining columns  
        for i in range(k,m) : 
            print(a[i][n-1],end=" ") 
        n -= 1
        # Print the last row from 
        # the remaining rows  
        if(k<m):     
            for i in range(n-1,(l-1),-1) : 
                print(a[m-1][i], end = " ") 
            m-=1
        # Print the first column from 
        # the remaining columns  
        if(l<n):
            for i in range(m - 1, k - 1, -1) : 
                print(a[i][l],end=" ")
            l+=1
  
# Driver Code 
R=int(input("Enter the number of rows:"))
C=int(input("Enter the number of columns:"))
a=[]
print("Enter the elements of the matrix:")
for i in range(R):
    l=list(map(int,input().split(" ")))
    a.append(l)
print("The elements are taken out from the matrix in the clockwise spiral direction.")
spiralPrint(R,C,a)

OUTPUT 1:

Enter the number of rows:3
Enter the number of columns:3
Enter the elements of the matrix:
1 2 3
4 5 6
7 8 9
The elements are taken out from the matrix in the clockwise spiral direction.
1 2 3 6 9 8 7 4 5

OUTPUT 2:

Enter the number of rows:4
Enter the number of columns:4
Enter the elements of the matrix:
1 2 3 4
4 5 6 7
7 8 9 1
2 3 6 4
The elements are taken out from the matrix in the clockwise spiral direction.
1 2 3 4 7 1 4 6 3 2 7 4 5 6 9 8

So, hope this tutorial helped you to clear your doubts.

Also Read,

Leave a Reply

Your email address will not be published. Required fields are marked *