leetcode-master
leetcode-master copied to clipboard
59.螺旋矩阵II 可以合并并行的多个循环
同样用的左闭右开:
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
num = 1
outer_len = side_len = n
mat = [[0 for j in range(side_len)] for i in range(side_len)]
for layer in range((n+1)//2):
for i in range(side_len-1):
# This part
mat[layer][i+layer] = num+i
mat[i+layer][outer_len-layer-1] = num+side_len-1+i
mat[outer_len-layer-1][outer_len-layer-1-i] = num+side_len*2-2+i
mat[outer_len-layer-1-i][layer] = num+side_len*3-3+i
if side_len == 1:
mat[n//2][n//2] = n**2
num += side_len*4-4
side_len -= 2
return mat
作为对比,你们团队的代码:
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
nums = [[0] * n for _ in range(n)]
startx, starty = 0, 0 # 起始点
loop, mid = n // 2, n // 2 # 迭代次数、n为奇数时,矩阵的中心点
count = 1 # 计数
for offset in range(1, loop + 1) : # 每循环一层偏移量加1,偏移量从1开始
for i in range(starty, n - offset) : # 从左至右,左闭右开
nums[startx][i] = count
count += 1
for i in range(startx, n - offset) : # 从上至下
nums[i][n - offset] = count
count += 1
for i in range(n - offset, starty, -1) : # 从右至左
nums[n - offset][i] = count
count += 1
for i in range(n - offset, startx, -1) : # 从下至上
nums[i][starty] = count
count += 1
startx += 1 # 更新起始点
starty += 1
if n % 2 != 0 : # n为奇数时,填充中心点
nums[mid][mid] = count
return nums
nice
还有更简洁的解法,先定义好前进的方向,“右-下-左-上”,当前进方向上不能继续时(超出数组或者已经被填充),就换到下一个方向继续前进。只需要一个循环和一个if就能完成
var generateMatrix = function(n) {
let x = 0, y = 0, current = 1, last = n * n;
const xDirections = [1, 0, -1, 0]; // 1表示向右,0表示横向不移动,-1表示向左
const yDirections = [0, 1, 0, -1]; // 1表示向下,0表示纵向不移动,-1表示向上
let directionIndex = 0;
const result = Array(n);
for(let i = 0; i < n; i++) {
result[i] = [];
}
while(current <= last) {
result[y][x] = current;
const nextX = x + xDirections[directionIndex];
const nextY = y + yDirections[directionIndex];
// 超出边界或者下一个位置已经填充过,就换方向
if (nextX < 0 || nextX >= n || nextY < 0 || nextY >= n || result[nextY][nextX]) {
directionIndex = (++directionIndex)%4;
}
x = x + xDirections[directionIndex];
y = y + yDirections[directionIndex];
current++;
}
return result;
};