publicclassSolution {
publicint[][]generateMatrix(int n) {
int[][] ans =newint[n][n];
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
int num = 1;
while (num <= n * n) {
for (int i = left; i<= right; i++) {
ans[top][i]= num++;
}
top++;
for (int i = top; i<= bottom; i++) {
ans[i][right]= num++;
}
right--;
for (int i = right; i >= left; i--) {
ans[bottom][i]= num++;
}
bottom--;
for (int i = bottom; i >= top; i--) {
ans[i][left]= num++;
}
left++;
}
return ans;
}
}
classSolution:
defgenerateMatrix(self, n: int) -> List[List[int]]:
# Step 1: Initialise an n x n matrix with zeros matrix: List[List[int]] = [[0] * n for _ in range(n)]
# Step 2: Define boundaries top, bottom, left, right =0, n -1, 0, n -1 num =1# Start filling with 1# Step 3: Traverse the boundarieswhile num <= n * n:
# Traverse top row (left to right)for col in range(left, right +1):
matrix[top][col] = num
num +=1 top +=1# Shrink top boundary# Traverse right column (top to bottom)for row in range(top, bottom +1):
matrix[row][right] = num
num +=1 right -=1# Shrink right boundary# Traverse bottom row (right to left)for col in range(right, left -1, -1):
matrix[bottom][col] = num
num +=1 bottom -=1# Shrink bottom boundary# Traverse left column (bottom to top)for row in range(bottom, top -1, -1):
matrix[row][left] = num
num +=1 left +=1# Shrink left boundaryreturn matrix