
Sponsored
Sponsored
This approach involves iteratively filling the matrix in a spiral pattern while maintaining boundary limits. We initialize four boundaries: top, bottom, left, and right. Starting with top as 0 and so on, we fill the elements from 1 to n2 within these boundaries:
This process repeats until all numbers are placed in the matrix.
Time Complexity: O(n^2), as we iterate through every cell of the matrix.
Space Complexity: O(1) for in-place modification, excluding the space required for the output matrix.
1def generateMatrix(n):
2 matrix = [[0]*n for _ in range(n)]
3 num = 1
4 top, bottom,
This Python function dynamically adjusts the top, bottom, left, and right pointers to fill the matrix in a spiral way using a while loop. The algorithm completes filling from 1 to n2.