
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 <vector>
2using namespace std;
3
4vector<vector<int>> generateMatrix(int n) {
5 vector<vector<int>> matrix(n, vector<int>(n));
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;
}The function leverages an iterative approach to fill the matrix based on boundary constraints. It incrementally fills values from 1 to n2 by modifying the boundaries after each complete traversal sequence.