# 59. Spiral Matrix II

{% embed url="<https://leetcode.com/problems/spiral-matrix-ii/>" %}

Array操作，问题核心应该是赋值loop的方向切换，我思路是维护四个数值来确定边界，到边界就转向。

```python
class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        res = [[0 for _ in range(n)] for _ in range(n)]
        val = 1
        l, r, u, d = 0, n-1, 0, n-1
        while True:
            for col in range(l, r+1):
                res[u][col] = val
                val += 1
            u += 1
            if u > d: break
            
            for row in range(u, d+1):
                res[row][r] = val
                val += 1
            r -= 1
            if r < l: break
            
            for col in range(r, l-1, -1):
                res[d][col] = val
                val += 1
            d -= 1
            if d < u: break
                
            for row in range(d, u-1, -1):
                res[row][l] = val
                val += 1
            l += 1
            if l > r: break
        
        return res
```
