网页设计网站制作收获,推广文章,闸北区网站建设网页制作,网站建设的原则 流程给定一个正整数 n#xff0c;生成一个包含 1 到 n^2 所有元素#xff0c;且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解#xff1a;
class Solution {public int[][] generateMatrix(int n) {int[][] ar…给定一个正整数 n生成一个包含 1 到 n^2 所有元素且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解
class Solution {public int[][] generateMatrix(int n) {int[][] arr new int[n][n]; // 创建 n * n 数组
int topRow 0, bottomRow n - 1; // 定义上边界和下边界int leftCol 0, rightCol n - 1; // 定义左边界和右边界int direction 0; // 初始方向0代表向右
int num 1; // 要赋的值
while (topRow bottomRow leftCol rightCol) {if (direction 0) { // 向右for (int i leftCol; i rightCol; i) {arr[topRow][i] num;}topRow; // 上边界下移} else if (direction 1) { // 向下for (int i topRow; i bottomRow; i) {arr[i][rightCol] num;}rightCol--; // 右边界左移} else if (direction 2) { // 向左for (int i rightCol; i leftCol; i--) {arr[bottomRow][i] num;}bottomRow--; // 下边界上移} else if (direction 3) { // 向上for (int i bottomRow; i topRow; i--) {arr[i][leftCol] num;}leftCol; // 左边界右移}direction (direction 1) % 4; // 切换方向}return arr;}
}
另解
class Solution {public int[][] generateMatrix(int n) {int loop 0; // 控制循环次数int[][] res new int[n][n];int start 0; // 每次循环的开始点(start, start)int count 1; // 定义填充数字int i, j;
while (loop n / 2) { // 判断边界后loop从1开始// 模拟上侧从左到右for (j start; j n - loop; j) {res[start][j] count;}
// 模拟右侧从上到下for (i start; i n - loop; i) {res[i][j] count;}
// 模拟下侧从右到左for (; j loop; j--) {res[i][j] count;}
// 模拟左侧从下到上for (; i loop; i--) {res[i][j] count;}start;}
if (n % 2 1) {res[start][start] count;}
return res;}
}