给你一个正整数 n
,生成一个包含 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)); // 构建二维数组,全赋值为0int 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 = 0start_y = 0offset = 1count = 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] = countcount += 1for i in range(start_x, n - offset):nums[i][n - offset] = countcount += 1for i in range(n - offset, start_y, -1):nums[n - offset][i] = countcount += 1for i in range(n - offset, start_x, -1):nums[i][start_y] = countcount += 1start_x += 1start_y += 1offset += 1if n % 2 == 1:nums[n//2][n//2] = countreturn nums