正の整数を指定するとn
、時計回りの順序で螺旋状に配置された to のすべての要素を1
含む正方行列を生成します。n2
n x n
matrix
例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
例 2:
输入:n = 1
输出:[[1]]
ヒント:
1 <= n <= 20
- 二分法と同じ考え方を使用してループの不変条件を決定し、ループが左閉じて右が開いているのか、左が閉じて右が閉じているのかを決定します。今回は左が閉じて右が開いています。
C++
成し遂げる:
#include "array_algorithm.h"
vector<vector<int>> generateMatrix(int n) {
int loop_num = n / 2; // 螺旋循环的圈数
int start_x = 0; // 矩阵行的起始位置
int start_y = 0; // 矩阵列的起始位置
int offset = 1; // 选用左开右闭原则,偏移
int count = 1; // 赋值参数
vector<vector<int>> nums(n, vector<int>(n, 0)); // 构建二维数组,全赋值为0
int i;
int j;
while (loop_num--)
{
i = start_x;
j = start_y;
for (j = start_y; j < n - offset; j++) {
nums[start_y][j] = count++;
}
for (i = start_x; i < n - offset; i++) {
nums[i][j] = count++;
}
for (; j > start_y; j--) {
nums[i][j] = count++;
}
for (; i > start_x; i--) {
nums[i][j] = count++;
}
start_x++;
start_y++;
offset += 1;
}
if (n % 2 == 1) {
nums[n / 2][n / 2] = count;
}
return nums;
}
python
成し遂げる:
def generateMatrix(n: int):
loop_nums = int(n // 2)
start_x = 0
start_y = 0
offset = 1
count = 1
# nums = np.random.randint(low=0, high=1, size=(n , n))
nums = [[0] * n for _ in range(n)]
for _ in range(loop_nums):
for i in range(start_y, n - offset):
nums[start_x][i] = count
count += 1
for i in range(start_x, n - offset):
nums[i][n - offset] = count
count += 1
for i in range(n - offset, start_y, -1):
nums[n - offset][i] = count
count += 1
for i in range(n - offset, start_x, -1):
nums[i][start_y] = count
count += 1
start_x += 1
start_y += 1
offset += 1
if n % 2 == 1:
nums[n//2][n//2] = count
return nums