王廷瑋|數位醫療|智慧醫療: 59. Spiral Matrix II WFU

2024年7月4日 星期四

59. Spiral Matrix II

59. Spiral Matrix II


給定一個正整數 n,生成一個 n x n 的矩陣,元素按 1 到 n^2 以螺旋順序填充。

範例 1:

輸入:n = 3 輸出:[[1,2,3],[8,9,4],[7,6,5]]


Python


from typing import List

class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
# Initialize an n x n matrix filled with zeros
matrix = [[0] * n for _ in range(n)]
# Define the initial boundaries
top, bottom, left, right = 0, n - 1, 0, n - 1
num = 1
while top <= bottom and left <= right:
# Fill the top row
for j in range(left, right + 1):
matrix[top][j] = num
num += 1
top += 1
# Fill the right column
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
# Fill the bottom row
if top <= bottom:
for j in range(right, left - 1, -1):
matrix[bottom][j] = num
num += 1
bottom -= 1
# Fill the left column
if left <= right:
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
return matrix

16.38MB, 44ms


C++


#include <vector>

using namespace std;

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
// Initialize an n x n matrix filled with zeros
vector<vector<int>> matrix(n, vector<int>(n, 0));
// Define the initial boundaries
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
// Fill the top row
for (int j = left; j <= right; ++j) {
matrix[top][j] = num++;
}
top++;
// Fill the right column
for (int i = top; i <= bottom; ++i) {
matrix[i][right] = num++;
}
right--;
// Fill the bottom row
if (top <= bottom) {
for (int j = right; j >= left; --j) {
matrix[bottom][j] = num++;
}
bottom--;
}
// Fill the left column
if (left <= right) {
for (int i = bottom; i >= top; --i) {
matrix[i][left] = num++;
}
left++;
}
}
return matrix;
}
};

7.65MB, 0ms


Javascript


/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
// Initialize an n x n matrix filled with zeros
const matrix = Array.from({ length: n }, () => Array(n).fill(0));
let top = 0, bottom = n - 1, left = 0, right = n - 1;
let num = 1;

while (top <= bottom && left <= right) {
// Fill the top row
for (let j = left; j <= right; j++) {
matrix[top][j] = num++;
}
top++;

// Fill the right column
for (let i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
right--;

// Fill the bottom row
if (top <= bottom) {
for (let j = right; j >= left; j--) {
matrix[bottom][j] = num++;
}
bottom--;
}

// Fill the left column
if (left <= right) {
for (let i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
left++;
}
}

return matrix;
};

49.19MB, 58ms