
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.
1#include <stdio.h>
2#include <stdlib.h>
3
4int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
The function generateMatrix initializes a 2D array of size n x n and fills it in spiral order using boundary markers. The loop continues until all elements are filled, adjusting the boundaries as needed after each direction traversal.