Print matrix in spiral form

method-1

m=int(input("number of rows"))

n=int(input("number of coulmns"))

a=[]

for i in range(m):

    a.append([int(j) for j in input().split()])  

rs=0

cs=0

while rs<m and cs<n:

    for i in range(n):

        print(a[rs][i],end=" ")

    rs+=1

    for i in range(rs,m):

        print(a[i][n-1],end=" ")

    n-=1

    if rs<m:

        for i in range(n-1,cs-1,-1):

            print(a[m-1][i],end=" ")

        m-=1

    if cs<n:

        for i in range(m-1,rs,-1):

            print(a[i][cs],end=" ")

        cs+=1


Method-2

m=int(input("number of rows"))

n=int(input("number of coulmns"))

a=[]

for i in range(m):

    a.append([int(j) for j in input().split()])  

res = []

turn = 0

while len(a) != 0 and len(a[0]) != 0:

    if turn % 4 == 0:

        res += a.pop(0)  

    if turn % 4 == 1:

        for i in range(len(a)):

            res.append(a[i].pop())


    if turn % 4 == 2: 

        res += a.pop()[::-1]

                

    if turn % 4 == 3: 

        for i in range(len(a))[::-1]:

            res.append(a[i].pop(0))

    turn += 1

print(res,end=" ")


Input:

number of rows3

number of coulmns4

1 2 3 4

5 6 7 8

9 10 11 12


Output:

[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] 

No comments:

Post a Comment