Print matrix in diagonal pattern | Python 3 program to print matrix in diagonal order ; Initialize indexes of element to be printed next ; Direction is initially from down to up ; Traverse the matrix till all elements get traversed ; If isUp = True then traverse from downward to upward ; Set i and j according to direction ; If isUp = 0 then traverse up to down ; Set i and j according to direction ; Revert the isUp to change the direction ; Driver program
MAX = 100 NEW_LINE def printMatrixDiagonal ( mat , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE isUp = True NEW_LINE while k < n * n : NEW_LINE INDENT if isUp : NEW_LINE INDENT while i >= 0 and j < n : NEW_LINE INDENT print ( str ( mat [ i ] [ j ] ) , end = " ▁ " ) NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE i -= 1 NEW_LINE DEDENT if i < 0 and j <= n - 1 : NEW_LINE INDENT i = 0 NEW_LINE DEDENT if j == n : NEW_LINE INDENT i = i + 2 NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT while j >= 0 and i < n : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " ▁ " ) NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT if j < 0 and i <= n - 1 : NEW_LINE INDENT j = 0 NEW_LINE DEDENT if i == n : NEW_LINE INDENT j = j + 2 NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT isUp = not isUp NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE n = 3 NEW_LINE printMatrixDiagonal ( mat , n ) NEW_LINE DEDENT