
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.
1public class Solution {
2 public int[][] GenerateMatrix(int n) {
3 int[][] matrix = new int[n][];
4 for (int i = 0; i < n; i++) matrix[i] = new int[n];
5
6 int num = 1, top = 0, bottom = n - 1, left = 0, right = n - 1;
7 while (num <= n * n) {
8 for (int i = left; i <= right; i++) matrix[top][i] = num++;
9 top++;
10 for (int i = top; i <= bottom; i++) matrix[i][right] = num++;
11 right--;
12 if (top <= bottom) {
13 for (int i = right; i >= left; i--) matrix[bottom][i] = num++;
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) matrix[i][left] = num++;
left++;
}
}
return matrix;
}
}This C# method adopts a similar iterative spiral filling pattern by managing boundaries and iterating through the 2D array until completion. The method outputs a filled spiral matrix.