Given a positive integer N, the task is to print an N × N zig-zag matrix consisting of numbers from 1 to N2, such that the ZigZag traversal of the matrix yields the number in ascending order.
Input: N = 4
1 2 4 7
3 5 8 11
6 9 12 14
10 13 15 16
The required matrix can be broken down into two right angle triangles.
- An upside down right angled triangle(considered as upper triangle).
- A normal right angled triangle(considered as lower triangle).
The idea is to iterate two nested loop to fill the upper triangle with respective values. Then iterate two nested loop again to fill the lower triangle with respective values. After the above two operations print the desired matrix.
Below is the implementation of the above approach:
1 2 4 7 3 5 8 11 6 9 12 14 10 13 15 16
Time Complexity: O(N2)
Auxillary Space: O(N2)
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.
- Sorting rows of matrix in ascending order followed by columns in descending order
- Sorting rows of matrix in descending order followed by columns in ascending order
- Sort Matrix in alternating ascending and descending order rowwise
- Zigzag (or diagonal) traversal of Matrix
- Largest sum Zigzag sequence in a matrix
- Print a given matrix in zigzag form
- Check if it is possible to rearrange rectangles in a non-ascending order of breadths
- C program to sort an array in ascending order
- Sort an array of Roman Numerals in ascending order
- Euler zigzag numbers ( Alternating Permutation )
- ZigZag Tree Traversal
- Program to print the Zigzag pattern
- Reverse zigzag Traversal of a Binary Tree
- Length of the longest ZigZag subarray of the given array
- Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles
- Arrange given numbers to form the smallest number
- Count number of ways to arrange first N numbers
- Arrange numbers to form a valid sequence
- Arrange the numbers in the Array as per given inequalities
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : kundudinesh007