Open In App

Python Program for Print matrix in zag-zag fashion

Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. 
 



Example: 
 

Input: 
1 2 3
4 5 6
7 8 9
Output: 
1 2 4 7 5 3 6 8 9

 



Method 1:
Approach of Python3 code 
This approach is simple. While travelling the matrix in the usual fashion, on basis of parity of the sum of the indices of the element, add that particular element to the list either at the beginning or at the end if sum of i and j is either even or odd respectively. Print the solution list as it is. 
 




# Program to print matrix in Zig-zag pattern
 
matrix = [
    [1, 2, 3, ],
    [4, 5, 6],
    [7, 8, 9],
]
rows = 3
columns = 3
 
solution = [[] for i in range(rows+columns-1)]
 
for i in range(rows):
    for j in range(columns):
        sum = i+j
        if(sum % 2 == 0):
 
            # add at beginning
            solution[sum].insert(0, matrix[i][j])
        else:
 
            # add at end of the list
            solution[sum].append(matrix[i][j])
 
 
# print the solution as it as
for i in solution:
    for j in i:
        print(j, end=" ")

Output
1 2 4 7 5 3 6 8 9 

Time complexity: O(n*m) for a given matrix of order n*m

Auxiliary Space: O(n*m)

Method 2: Using While loop
 




# Program to print matrix in Zig-zag pattern
 
 
def findOrder(matrix):
    rows = 3
    columns = 3
    result = [0]*(rows*columns)
    result[0] = matrix[0][0]
    k = 1
    i = j = 0
    while(k < rows*columns):
        while i >= 1 and j < rows-1:
            i -= 1
            j += 1
            result[k] = matrix[i][j]
            k += 1
        if j < rows-1:
            j += 1
            result[k] = matrix[i][j]
            k += 1
        elif i < columns-1:
            i += 1
            result[k] = matrix[i][j]
            k += 1
        while i < columns-1 and j >= 1:
            i += 1
            j -= 1
            result[k] = matrix[i][j]
            k += 1
        if i < columns-1:
            i += 1
            result[k] = matrix[i][j]
            k += 1
        elif j < rows-1:
            j += 1
            result[k] = matrix[i][j]
            k += 1
    return result
 
 
matrix = [
    [1, 2, 3, ],
    [4, 5, 6],
    [7, 8, 9],
]
rows = 3
columns = 3
result = findOrder(matrix)
for num in result:
    print(num, end=' ')

Output
1 2 4 7 5 3 6 8 9 

Time Complexity: O(rows*columns),The time complexity of the algorithm is O(rows*columns) since we are iterating through the matrix of size rows*columns. 
Space Complexity: O(rows*columns),The space complexity of the algorithm is O(rows*columns) since we are creating an array of size rows*columns to store the result.

Please refer complete article on Print matrix in zag-zag fashion for more details!
 


Article Tags :