
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.
1class Solution {
2 public int[][] generateMatrix(int n) {
3 int[][] matrix = new int[n][This Java method fills a 2D integer array in a spiral pattern using directional movements dictated by boundary adjustments. It iterates until all elements from 1 to n2 are placed.