华为OD机试 - 螺旋数字矩阵(Java & JS & Python & C & C++)
题目描述:
给定一个正整数 n,生成一个包含 1 到 n^2 所有整数的矩阵,但是矩阵是由外向内螺旋状地填充的。
示例:
输入 n = 3
输出
[[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
解法1:模拟螺旋填充过程(Java)
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int start = 0;
int count = 1;
int loop = n / 2;
int mid = n / 2;
int offset = 1;
int i, j;
while (loop-- > 0) {
i = start;
j = start;
// left to right
for (j = start; j < n - offset; j++) {
matrix[start][j] = count++;
}
// top to bottom
for (i = start; i < n - offset; i++) {
matrix[i][j] = count++;
}
// right to left
for (; j > start; j--) {
matrix[i][j] = count++;
}
// bottom to top
for (; i > start; i--) {
matrix[i][j] = count++;
}
start++;
offset += 1;
}
if (n % 2 == 1) {
matrix[mid][mid] = count;
}
return matrix;
}
}
解法2:优化空间复杂度(Python)
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0] * n for _ in range(n)]
start = 0
count = 1
loop = n // 2
mid = n // 2
offset = 1
while loop:
i = j = start
# left to right
for j in range(start, n - offset):
matrix[start][j] = count
count += 1
# top to bottom
for i in range(start, n - offset):
matrix[i][j] = count
count += 1
# right to left
for j in range(n - offset, start, -1):
matrix[i][j] = count
count += 1
# bottom to top
for i in range(n - offset, start, -1):
matrix[i][j] = count
count += 1
start += 1
offset += 1
loop -= 1
if n % 2:
matrix[mid][mid] = count
return matrix
解法3:C++版本
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<in
评论已关闭