Infytq 2022 on Spiral Matrix
In this class, We discuss Infytq 2022 on Spiral Matrix.
For Complete YouTube Video: Click Here
The reader should have prior knowledge of the spiral matrix. Click Here.
Consider a 2D integer matrix inmatrix of size mxn. identify and print an integer array outarr using the below logic
. Traverse through the inmatrix in a counter-clockwise spiral direction starting from the element at (0,0)
A counterclockwise spiral traversal of a matrix is one where traversal starts with an element then moves down, then right, then top, then left, and so on
such that:
1) each element is visited only once
2) the direction will change only when there is no element left to visit in the current direction
. During the counterclockwise spiral traversal keep adding the elements in a temparr in the
order of occurrence until the sum of the elements in temparr leads to an automaorphic number
with a length of temparr greater than 1.
A number num is said to be automorphic if and only if the square ends with num
. add temparr elements in the order of traversal to outarr
. start the traversal again from the next element to be visited by emptying the temparr
. repeat the steps until all the elements have been visited
Note: There would be at least one temparr whose sum of elements would be an automorphic number
Input Format:
First-line will contain the number of rows m of inmatrix
The next m lines contain the elements of inmatrix
each line will have n elements separated by ‘,’ (comma)
Output:
print outarr elements seperated by ‘,’ (comma) to the standard output stream
Sample
3
1, 2, -2, 0
5, -3, 2, 7
0, 1, 0, 1
Output
1,5,0,1,0,1,7,0,-2,2,-3,2
sample 2
3
7, 4, 9
2, -1, 6
0, -9, 1
Output:
7, 2, 0, -9
Code in Python:
def automorphic(x):
global temparr,summ,outarr
temparr.append(x)
summ=summ+x
if((len(temparr)>1)and(summ>=0)):
i=0
val=summ
sval=summ*summ
while(val!=0):
j=val%10
k=sval%10
val=int(val/10)
sval=int(sval/10)
if(j!=k):
i=1
break
if(i==0):
outarr+=temparr
temparr.clear()
summ=0
m = int(input(‘enter the number of rows’))
inmatrix=[]
temparr=[]
outarr=[]
summ=0
for i in range(m):
lis=list(map(int,input().split(‘,’)))
inmatrix.append(lis)
print(inmatrix)
n=len(inmatrix[0])
top = left = 0
bottom = m-1
right = n-1
while True:
if(top>bottom):
break
i=top
j=left
while(i<=bottom):
automorphic(inmatrix[i][j])
i=i+1
left= left+1
if(left>right):
break
i=bottom
j=left
while(j<=right):
automorphic(inmatrix[i][j])
j=j+1
bottom=bottom-1
if(top>bottom):
break
i=bottom
j=right
while(i>=top):
automorphic(inmatrix[i][j])
i=i-1
right=right-1
if(left>right):
break
i=top
j=right
while(j>=left):
automorphic(inmatrix[i][j])
j=j-1
top=top+1
print(outarr)