原题链接:59. Spiral Matrix II
【思路】
遍历图解如上图所示,n 分为偶数和奇数两种情况。当 n 为偶数时,最后一次遍历刚好添加完毕;当 n 为奇数时,最后还需要进行一次添加操作⑤。另外,注意我所定义的 x 方向是竖向,y 方向是横向的。
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.