Spiral Matrix

In this class, we discuss the spiral matrix.

For Complete YouTube Video: Click Here

The reader should have some basic coding knowledge to continue with this class.

This coding question is a medium-level question.

Please complete our placement training for a service-based course to improve your basic coding knowledge. Click Here.

The examples we discussed in the placement training course will help improve basic-level coding skills.

We give a graphical intuition on how to write code for the spiral matrix.

The best practice is to write the code independently and then check the solution.

Input is to take a matrix of size m x n.

The below diagram shows how to move in the spiral direction in the given matrix.

Output the elements in the order of spiral rotation in the matrix.

Output: 1,2,3,4,8,12,16,20,19,18,17,13,9,5,6,7,11,15,14,10

Logic: Take four variables top, bottom, left, and right.

The top variable always points to the top line, which is not displayed.

Similarly, the right variable points to the right column not yet displayed.

The left and bottom also point left column and bottom row respectively.

Initially top has a value of zero.

First, we need to display a zeroth line, and after display, the top has a value one.

After displaying the top line, we need to display the right column, bottom line, and left column.

To display the above four actions. We need four loops.

The four loops should be repeated till there are no more data to display.

How do we identify all the data is displayed?

When the top variable value is greater than the bottom variable value or the left variable value is greater than the right variable value.

We follow the above conditions to stop the loop.

The below program shows the complete code.

import numpy as np

m = int(input(‘enter the number of lines in matrix’))

n = int(input(‘enter the number of columns in the matrix’))

top = left = 0

bottom = m-1

right = n-1

a = np.empty((m,n))

for i in range(m):

    for j in range(n):

        a[i][j]=int(input())

print(a)

while True:

    if(left > right):

        break

    i=top

    j=left

    while(j<=right):

        print(a[i][j], end = ” “)

        j=j+1

    top=top+1

    if(top > bottom):

        break

    i=top

    j=right

    while(i<=bottom):

        print(a[i][j], end = ” “)

        i=i+1

    right=right-1

    if(left>right):

        break

    i=bottom

    j=right

    while j>=left:

        print(a[i][j],end =” “)

        j=j-1

    bottom=bottom-1

    if(top>bottom):

        break

    i=bottom

    j=left

    while(i>=top):

        print(a[i][j],end = ” “)

        i=i-1

    left=left+1

We take an infinite loop, and in the infinite loop, we write the four loops required for four actions.

We come out of the infinite loop using the above conditions and a break statement.