珠海做网站公司,wordpress定时功能,wordpress 图书主题,基础很差去公司做网站这里写自定义目录标题 一、题目二、解题精髓-循环不变量三、代码 一、题目
给定⼀个正整数 n#xff0c;⽣成⼀个包含 1 到 n^2 所有元素#xff0c;且元素按顺时针顺序螺旋排列的正⽅形矩阵。 示例: 输⼊: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
二、解题精髓… 这里写自定义目录标题 一、题目二、解题精髓-循环不变量三、代码 一、题目
给定⼀个正整数 n⽣成⼀个包含 1 到 n^2 所有元素且元素按顺时针顺序螺旋排列的正⽅形矩阵。 示例: 输⼊: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
二、解题精髓-循环不变量
⽽求解本题依然是要坚持循环不变量原则。
在循环遍历每一条边的时候都坚持左闭右开的原则
三、代码
class GenerateMatrix {public static int[][] generateMatrix(int n) {int[][] nums new int[n][n];int startx 0, starty 0, offset 1, count 1;int x 0, y 0;while (offset n / 2) {for (x startx; x n - offset; x) {nums[starty][x] count;}for (y starty; y n - offset; y) {nums[y][x] count;}for (; x startx; x--) {nums[y][x] count;}for (; y starty; y--) {nums[y][x] count;}startx;starty;offset;}if (n % 2 1) {nums[starty][startx] count;}return nums;}public static void main(String[] args) {int n 4;int[][] res GenerateMatrix.generateMatrix(n);for (int i 0; i n; i) {for (int j 0; j n; j) {System.out.print(res[j][i] );}System.out.println();}}
}