59.螺旋矩阵 II
解题思路
初看,毫无头绪。
打开官方答案领会一下。
整体采用构建矩阵,填充矩阵的思路,填充过程分为四种情况:
- 从左到右填充一行
- 从上到下填充一列
- 从右到左填充一行,注意只有一行的情况
- 从下到上填充一列,注意只有一列的情况
出现的问题
JavaScript解法代码
var generateMatrix = function(n) {
let num = 1;
const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0));
let left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
// 从左上至右上
for (let column = left; column <= right; column++) {
matrix[top][column] = num;
num++;
}
// 从右上至右下
for (let row = top + 1; row <= bottom; row++) {
matrix[row][right] = num;
num++;
}
// 还没到最后一圈
if (left < right && top < bottom) {
// 从右下至左下
for (let column = right - 1; column > left; column--) {
matrix[bottom][column] = num;
num++;
}
// 从左下至左上
for (let row = bottom; row > top; row--) {
matrix[row][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
};
Python解法代码
import numpy as np
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = np.zeros((n, n))
num = 1
left=0
right=n-1
top=0
bottom=n-1
while(left <= right and top <= bottom):
for i in range(left,right+1):
matrix[top][i] = num
num += 1
for j in range(top+1,bottom+1):
matrix[j][right] = num
num += 1
if(left < right and top < bottom):
for i in range(right-1,left,-1):
matrix[bottom][i] = num
num += 1
for j in range(bottom,top,-1):
matrix[j][left] = num
num += 1
left += 1
right -= 1
top += 1
bottom -= 1
# convert the matrix to integer type and then to a list
matrix = matrix.astype(int).tolist()
return matrix
总结:
- 注意数组的初始化:
nums = [[0] * n for _ in range(n)] # 创建一个大小为n的二维数组,初始值都为0
const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0));
matrix = np.zeros((n, n))