59.螺旋矩陣 II
解題思路
初看袄友,毫無頭緒晓殊。
打開官方答案領(lǐng)會一下客情。
整體采用構(gòu)建矩陣庸追,填充矩陣的思路朱盐,填充過程分為四種情況:
- 從左到右填充一行
- 從上到下填充一列
- 從右到左填充一行购桑,注意只有一行的情況
- 從下到上填充一列畅铭,注意只有一列的情況
出現(xiàn)的問題
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
總結(jié):
- 注意數(shù)組的初始化:
nums = [[0] * n for _ in range(n)] # 創(chuàng)建一個大小為n的二維數(shù)組,初始值都為0
const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0));
matrix = np.zeros((n, n))