59. Spiral Matrix II
Problem
Return an n×n matrix filled with 1…n² in clockwise spiral order, starting at the top-left.
Example: n = 3 → [[1,2,3],[8,9,4],[7,6,5]]
Same four boundaries as Spiral Matrix, but write 1..n² instead of reading.
Complexity: O(n²).
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
m = [[0] * n for _ in range(n)]
top, bottom, left, right, k = 0, n - 1, 0, n - 1, 1
while top <= bottom:
for c in range(left, right + 1):
m[top][c] = k; k += 1
for r in range(top + 1, bottom + 1):
m[r][right] = k; k += 1
for c in range(right - 1, left - 1, -1):
if top < bottom:
m[bottom][c] = k; k += 1
for r in range(bottom - 1, top, -1):
if left < right:
m[r][left] = k; k += 1
top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1
return m
assert Solution().generateMatrix(3) == [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
assert Solution().generateMatrix(1) == [[1]]
class Solution {
public int[][] generateMatrix(int n) {
int[][] m = new int[n][n];
int top = 0, bottom = n - 1, left = 0, right = n - 1, k = 1;
while (top <= bottom) {
for (int c = left; c <= right; c++) m[top][c] = k++;
for (int r = top + 1; r <= bottom; r++) m[r][right] = k++;
if (top < bottom) for (int c = right - 1; c >= left; c--) m[bottom][c] = k++;
if (left < right) for (int r = bottom - 1; r > top; r--) m[r][left] = k++;
top++; bottom--; left++; right--;
}
return m;
}
}
func generateMatrix(n int) [][]int {
m := make([][]int, n)
for i := range m {
m[i] = make([]int, n)
}
top, bottom, left, right, k := 0, n-1, 0, n-1, 1
for top <= bottom {
for c := left; c <= right; c++ {
m[top][c] = k
k++
}
for r := top + 1; r <= bottom; r++ {
m[r][right] = k
k++
}
if top < bottom {
for c := right - 1; c >= left; c-- {
m[bottom][c] = k
k++
}
}
if left < right {
for r := bottom - 1; r > top; r-- {
m[r][left] = k
k++
}
}
top, bottom, left, right = top+1, bottom-1, left+1, right-1
}
return m
}