Print Matrix - Diagonal Zig Zag

Print Matrix - Diagonal Zig Zag 

Problem:

An R*C matrix is passed as the input to the program. The program must print the values in zig-zag order diagonally. (Please refer Example Input/Output section for more details). 

Input Format: 

The first line contains R and C separated by a space. Next R lines contain C values separated by a space. 

Output Format: 

The first line contains all R*C elements in zig-zag order diagonally, with the elements separated by a space. 

Boundary Conditions: 

2 <= R, C <= 100 

Example Input/Output 1: 

Input: 

3 3 

1 2 3 

4 5 6 

7 8 9 

Output: 

1 2 4 7 5 3 6 8 9 

Example Input/Output 2: 

Input: 

3 7 

1 2 3 4 5 6 7 

8 9 1 2 3 4 5 

6 7 8 9 1 2 3 

Output: 

1 2 8 6 9 3 4 1 7 8 2 5 6 3 9 1 4 7 5 2 3

Program:

r,c = map(int,input().split())

l = []

for i in range(r):

    l.append(list(map(int,input().split())))

k = [] 

for i in range(r): 

    x = i 

    y = 0

    p = []

    while x >= 0 and y < c:

        p.append(l[x][y])

        x -= 1 

        y += 1 

    k.append(p)

for i in range(1,c): 

    x = r-1 

    y = i 

    p = []

    while x >= 0 and y < c: 

        p.append(l[x][y])

        x -= 1 

        y += 1 

    k.append(p)    

for i in range(len(k)):

    if i%2 == 0:

        print(*k[i],end=" ")

    else:

        print(*k[i][::-1],end=" ")

Comments

Popular posts from this blog

Pronic Integers in N - InfyTQ question

Count Strong Points - Accenture

Letters at position of multiples of a number