很抱歉,您没有提供需要改写的句子。请提供您希望改写的句子,我将为您改写为一个长尾词的。
- 内容介绍
- 文章标签
- 相关推荐
本文共计327个文字,预计阅读时间需要2分钟。
题目:给定一个整数n,生成一个包含1到n^2所有元素的,元素按顺时针螺旋顺序排列的n×n正方形矩阵。
示例1:输入:n=3输出:[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
示例2:输入:n=1输出:[[1]]
题目:
给你一个正整数n ,生成一个包含 1 到n2所有元素,且元素按顺时针顺序螺旋排列的n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
代码实现:
class Solution {public int[][] generateMatrix(int n) {
int num = 1;
int[][] matrix = new int[n][n];
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
matrix[top][column] = num;
num++;
}
for (int row = top + 1; row <= bottom; row++) {
matrix[row][right] = num;
num++;
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
matrix[bottom][column] = num;
num++;
}
for (int row = bottom; row > top; row--) {
matrix[row][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
}
}
本文共计327个文字,预计阅读时间需要2分钟。
题目:给定一个整数n,生成一个包含1到n^2所有元素的,元素按顺时针螺旋顺序排列的n×n正方形矩阵。
示例1:输入:n=3输出:[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
示例2:输入:n=1输出:[[1]]
题目:
给你一个正整数n ,生成一个包含 1 到n2所有元素,且元素按顺时针顺序螺旋排列的n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
代码实现:
class Solution {public int[][] generateMatrix(int n) {
int num = 1;
int[][] matrix = new int[n][n];
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
matrix[top][column] = num;
num++;
}
for (int row = top + 1; row <= bottom; row++) {
matrix[row][right] = num;
num++;
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
matrix[bottom][column] = num;
num++;
}
for (int row = bottom; row > top; row--) {
matrix[row][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
}
}

