# leetcode 59. Spiral Matrix II-螺旋矩阵|清晰思路

【思路】

public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int num=1, d=n-1, x=(n-d)/2, y=(n-d)/2;
while (d > 0) {
for(int i=0; i<d; i++) res[x][y+i] = num++;  //①
y += d;
for(int i=0; i<d; i++) res[x+i][y] = num++;  //②
x += d;
for(int i=0; i<d; i++) res[x][y-i] = num++;  //③
y = (n-d) / 2;
for(int i=0; i<d; i++) res[x-i][y] = num++;  //④
d -= 2;
x = (n-d) / 2;
y = (n-d) / 2;
}
if (d==0) res[x][y] = num;  //⑤
return res;
}
}
21 / 21 test cases passed. Runtime: 0 ms  Your runtime beats 20.33% of javasubmissions.

Python 在语法上做了小小的优化，将4个循环合并：

class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res, step, x, y, num = [[0]*n for i in range(n)], n-1, 0, 0, 1
dx, dy = [0,1,0,-1], [1,0,-1,0]
while step > 0 :
for i in range(4) :
for j in range(step) :
res[x][y] = num
x, y, num = x+dx[i], y+dy[i], num+1
step -= 2
x,y = (n-step)/2, (n-step)/2
if step == 0 : res[x][y] = num
return res
21 / 21 test cases passed. Runtime: 60 ms  Your runtime beats 22.66% of pythonsubmissions.

04-24 129

08-07 1794

05-23 225

07-15 577

08-01 273

05-07 14

02-25 109

04-16 187

05-09 28

04-17 487