VOOZH about

URL: https://www.geeksforgeeks.org/dsa/circular-matrix-construct-a-matrix-with-numbers-1-to-mn-in-spiral-way/

⇱ Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)

Last Updated : 23 Jul, 2025

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:


Output
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)

Comment
Article Tags:
Article Tags: