# LeetCode 59. 螺旋矩阵 II（python、c++）

## 题目描述

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

(循环) O(n2)

c++版

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans;
ans = vector<vector<int>> (n, vector<int> (n));
int x = 0, y = 0;
int step = 1;
while(step <= n*n){

while(y < n && !ans[x][y])ans[x][y++] = step++;
y-=1;
x+=1;
while(x < n && !ans[x][y]) ans[x++][y] = step++;
x-=1;
y-=1;
while(y >= 0 &&!ans[x][y]) ans[x][y--] = step++;
y += 1;
x-=1;
while(x >= 0 && !ans[x][y]) ans[x--][y] = step++;
x+=1;
y+=1;
}
return ans;
}
};


python版

class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
ans = [[0 for _ in range(n)] for _ in range(n)]
x = 0
y = 0
step = 1
while step <= n*n:
while y < n and ans[x][y] == 0:
ans[x][y] = step;
y += 1
step += 1
y-=1;
x+=1;
while x < n and ans[x][y] == 0:
ans[x][y] = step;
x += 1
step += 1
x-=1;
y-=1;
while y >= 0 and ans[x][y] == 0:
ans[x][y] = step;
y -= 1
step += 1
y += 1;
x-=1;
while x >= 0 and ans[x][y] == 0:
ans[x][y] = step;
x -= 1
step += 1
x+=1;
y+=1;
return ans

04-17 1849
05-31 1621

09-11 115