Given an m x n integer matrix, peel it layer by layer from the outside in, the way a spiral traversal does. Each concentric rectangular boundary forms one layer. Return a list whose i-th element is the sum of all values on the i-th boundary, with the outermost layer at index 0.
Function Signature
def spiral_boundary_sum(matrix: list[list[int]]) -> list[int]:
...
Rules
-
matrix
is rectangular and non-empty: it has
m
rows and every row has
n
values.
-
Layer
d
lives in the sub-rectangle with rows
d
through
m - 1 - d
and columns
d
through
n - 1 - d
. Its boundary is every cell
(r, c)
of that sub-rectangle with
r == d
,
r == m - 1 - d
,
c == d
or
c == n - 1 - d
.
-
Layers continue inward while the sub-rectangle still contains at least one cell, so every cell of the matrix belongs to exactly one layer.
-
If a layer collapses to a single row, a single column or a single cell, each cell of that layer is counted exactly once.
-
Return the sums ordered from the outermost layer to the innermost.
Constraints
-
1 <= m, n <= 100
-
-1000 <= matrix[i][j] <= 1000
Examples
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [40,5]
The outer layer is 1 + 2 + 3 + 6 + 9 + 8 + 7 + 4 = 40. The inner layer is just the single cell 5.
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [65,13]
The outer boundary is 1 + 2 + 3 + 4 + 8 + 12 + 11 + 10 + 9 + 5 = 65. The inner layer collapses to the single row [6, 7], which sums to 13.
Input: matrix = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
Output: [96,24]
The outer boundary is 1 + 2 + 3 + 6 + 9 + 12 + 15 + 14 + 13 + 10 + 7 + 4 = 96. The inner layer collapses to the single column [5, 8, 11], which sums to 24.