Spiral Matrix II (M)
Given a positive integer n, generate a square matrix filled with elements from 1 to n 2 n^2 n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
题意
将数1- n 2 n^2 n2按照螺旋顺时针的顺序填入一个 n x n 的矩阵中。
思路
方法与 54. Spiral Matrix 一样,在实现细节上甚至更加简单。
代码实现
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int[] iPlus = {0, 1, 0, -1};
int[] jPlus = {1, 0, -1, 0};
int direction = 0; // 0123分别代表右下左上
int i = 0, j = 0;
for (int num = 1; num <= n * n; num++) {
matrix[i][j] = num;
// 先判断以当前方向走到的下一个位置是否合法,不合法则转向
int nextI = i + iPlus[direction];
int nextJ = j + jPlus[direction];
if (nextI == -1 || nextI == n || nextJ == -1 || nextJ == n || matrix[nextI][nextJ] != 0) {
direction = (direction + 1) % 4;
i += iPlus[direction];
j += jPlus[direction];
} else {
i = nextI;
j = nextJ;
}
}
return matrix;
}
}
代码实现 - 层遍历
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
// 四个参数确定四条外边
int rowUp = 0, rowDown = n - 1;
int colLeft = 0, colRight = n - 1;
int num = 1;
while (rowUp <= rowDown && colLeft <= colRight) {
for (int c = colLeft; c <= colRight; c++) {
matrix[rowUp][c] = num++;
}
for (int r = rowUp + 1; r <= rowDown; r++) {
matrix[r][colRight] = num++;
}
// 只有当前层不是一直线时,才有下边和左边
if (rowUp < rowDown && colLeft < colRight) {
for (int c = colRight - 1; c > colLeft; c--) {
matrix[rowDown][c] = num++;
}
for (int r = rowDown; r > rowUp; r--) {
matrix[r][colLeft] = num++;
}
}
// 四边向内推进一层
rowUp++;
rowDown--;
colLeft++;
colRight--;
}
return matrix;
}
}
本文介绍了一种算法,用于生成一个n×n的螺旋矩阵,矩阵元素从1到n²按螺旋顺序填充。提供了两种实现方式:通过方向变化和层遍历来完成矩阵填充,详细解析了代码实现过程。
812

被折叠的 条评论
为什么被折叠?



