
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Zigzag (or diagonal) traversal of Matrix in C++
In this problem, we are given a 2D matrix. Our task is to print all the elements of the matric in a diagonal order.
Let’s take an example to understand the problem,
1 2 3 4 5 6 7 8 9
Output −
1 4 2 7 5 3 8 6 9
Let’s see the pattern that is followed while printing the matrix in a zigzag form or diagonal form.
This is the way diagonal traversal works.
The number of lines in output is always dependent on the row and columns of the 2D matrix.
For a 2D matrix mat[r][c], their will be r+c-1 output lines.
Example
Now, let’s see the solution to the program,
#include <iostream> using namespace std; #define R 5 #define C 4 int min2(int a, int b) { return (a < b)? a: b; } int min3(int a, int b, int c) { return min2(min2(a, b), c);} int max(int a, int b) { return (a > b)? a: b; } void printDiagonalMatrix(int matrix[][C]){ for (int line=1; line<=(R + C -1); line++){ int start_col = max(0, line-R); int count = min3(line, (C-start_col), R); for (int j=0; j<count; j++) cout<<matrix[min2(R, line)-j-1][start_col+j]<<"\t"; cout<<endl; } } int main(){ int M[R][C] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20},}; cout<<"The matrix is : \n"; for (int i=0; i< R; i++){ for (int j=0; j<C; j++) cout<<M[i][j]<<"\t"; cout<<endl; } cout<<"\nZigZag (diagnoal) traversal of matrix is :\n"; printDiagonalMatrix(M); return 0; }
Output
The matrix is : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ZigZag (diagonal) traversal of matrix is : 1 5 2 9 6 3 13 10 7 4 17 14 11 8 18 15 12 19 16 20
- Related Articles
- ZigZag Tree Traversal in C++
- Binary Tree Zigzag Level Order Traversal in Python
- Diagonal Traversal of Binary Tree in C++?
- Kth node in Diagonal Traversal of Binary Tree in C++
- Print a given matrix in zigzag form in C++
- Print matrix in diagonal pattern
- Diagonal product of a matrix - JavaScript
- Program to check diagonal matrix and scalar matrix in C++
- Row-wise vs column-wise traversal of matrix in C++
- Program to convert given Matrix to a Diagonal Matrix in C++
- Convert a single column matrix into a diagonal matrix in R.
- Program to find diagonal sum of a matrix in Python
- Program to print a matrix in Diagonal Pattern.
- How to create a block diagonal matrix using a matrix in R?
- Print numbers in matrix diagonal pattern in C Program.

Advertisements