![]() |
VOOZH | about |
Given two values m and n, fill a matrix of size 'm*n' in a spiral (or circular) fashion (clockwise) with natural numbers from 1 to m*n.
Examples:
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 a spiral fashion. While traversing, we keep track of a variable "val" to fill the next value, we increment "val" one by one and put its values in the matrix.
Implementation:
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)