Print a given matrix in zigzag form
Given a 2D array, print it in zigzag form.
Examples :
Input : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Output : 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16 Input : 10 24 32 50 6 17 99 10 11 Output : 10 24 32 17 6 50 99 10 11
C++
// C++ program to print // matrix in zig-zag form #include <iostream> using namespace std; // Method to print matrix in zig-zag form void printZigZag( int row, int col, int a[][5]) { int evenRow = 0; //starts from the first row int oddRow = 1; //starts from the next row while (evenRow<row) { for ( int i=0;i<col;i++) { // evenRow will be printed // in the same direction cout<<a[evenRow][i] << " " ; } // Skipping next row so as // to get the next evenRow evenRow = evenRow + 2; if (oddRow < row) { for ( int i=col-1; i>=0; i--) { // oddRow will be printed in // the opposite direction cout<<a[oddRow][i] << " " ; } } // Skipping next row so as // to get the next oddRow oddRow = oddRow + 2; } } // Driver function int main() { int r = 3, c = 5;
Java
Python 3
C#
PHP
Output : 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 Time Complexity: Time complexity of the above solution is O(row*column). Related Articles: This article is contributed by Kamal Rawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. |