Given two values m and n, fill a matrix of size ‘m*n’ in spiral (or circular) fashion (clockwise) with natural numbers from 1 to m*n.
Input : m = 4, n = 4 Output : 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Input : m = 3, n = 4 Output : 1 2 3 4 10 11 12 5 9 8 7 6
The idea is based on Print a given matrix in spiral form. We create a matrix of size m * n and traverse it in spiral fashion. While traversing, we keep track of a variable “val” to fill next value, we increment “val” one by one and put its values in the matrix.
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
Time complexity: O(m * n)
Space complexity: O(m * n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Convert given Matrix into sorted Spiral Matrix
- Form a Spiral Matrix from the given Array
- Print a given matrix in spiral form
- Print a given matrix in reverse spiral form
- Print K'th element in spiral form of matrix
- Find the sum of the diagonal elements of the given N X N spiral matrix
- Sum of both diagonals of a spiral odd-order square matrix
- Print n x n spiral matrix using O(1) extra space
- Print a matrix in a spiral form starting from a point
- Print a given matrix in spiral form using direction tracking method
- Print a given matrix in counter-clock wise spiral form
- Construct a unique matrix n x n for an input n
- Construct a linked list from 2D matrix
- Construct tree from ancestor matrix
- Construct Ancestor Matrix from a Given Binary Tree
- Construct a matrix such that union of ith row and ith column contains every element from 1 to 2N-1
- Construct a linked list from 2D matrix (Iterative Approach)
- Construct a Matrix of size NxN with values in range [1, N^2] as per given conditions
- Check if all rows of a matrix are circular rotations of each other
- Construct a Doubly linked linked list from 2D Matrix