059._spiral_matrix_ii.md 1.8 KB
Newer Older
K
KEQI HUANG 已提交
1
### 59. Spiral Matrix II
K
KEQI HUANG 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

题目:
<https://leetcode.com/problems/spiral-matrix-ii/>


难度:
Medium

和Spiral Matrix的思路基本一致

也许还有待挖掘trick


K
KEQI HUANG 已提交
15
```python
K
KEQI HUANG 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
class Solution(object):
    def generateMatrix(self,n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        curNum = 0
        matrix = [[0 for i in range(n)] for j in range(n)]
        maxUp = maxLeft = 0 
        maxDown = maxRight = n - 1
        direction = 0                
        while True:
            if direction == 0: #go right
                for i in range(maxLeft, maxRight+1):
                    curNum += 1
                    matrix[maxUp][i] = curNum
                maxUp += 1
            elif direction == 1: # go down
                for i in range(maxUp, maxDown+1):
                    curNum += 1
                    matrix[i][maxRight] = curNum
                maxRight -= 1
            elif direction == 2: # go left
                for i in reversed(range(maxLeft, maxRight+1)):
                    curNum += 1 
                    matrix[maxDown][i] = curNum
                maxDown -= 1
            else: #go up
                for i in reversed(range(maxUp, maxDown+1)):
                    curNum += 1
                    matrix[i][maxLeft] = curNum
                maxLeft +=1
            if curNum >= n*n:
                return matrix
            direction = (direction + 1 ) % 4
K
KEQI HUANG 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64
```

Same idea with [spiral matrix I](https://github.com/Lisanaaa/thinking_in_lc/blob/master/054._spiral_matrix.md)
```python
class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        res = []
        l = n * n + 1
        while l > 1:
            l, r = l - len(res), l
K
KEQI HUANG 已提交
65
            res = [range(l, r)] + zip(*res[::-1])
K
KEQI HUANG 已提交
66 67
        return res
```