# Untitled

unknown
python
2 months ago
1.8 kB
6
Indexable
Never
```class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[-1] * n for _ in range(n)]
limit = n ** 2

r, c = 0, 0
matrix[r][c] = 1

rmax, cmax = n, n
rmin, cmin = 0, 0

count = 1

rmode, cmode = True, False
forward, backward, upward, downward = True, False, False, False

while True:
if rmode:
if forward:
for c in range(c+1, cmax):
count = count + 1
matrix[r][c] = count
forward, downward = False, True
rmin += 1

if backward:
for c in range(c-1, cmin-1, -1):
count = count + 1
matrix[r][c] = count
backward, upward = False, True
rmax -= 1

if count == limit:
return matrix
else:
rmode, cmode = False, True

if cmode:
if downward:
for r in range(r+1, rmax):
count = count + 1
matrix[r][c] = count
downward, backward = False, True
cmax -= 1

if upward:
for r in range(r-1, rmin-1, -1):
count = count + 1
matrix[r][c] = count
upward, forward = False, True
cmin += 1

if count == limit:
return matrix
else:
rmode, cmode = True, False

```