题目
-
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
-
For example,
Given n = 3, -
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
分析题目
- 本题要求以转圈的顺序填写矩阵,就相当于是转圈打印矩阵的类似逆运算。本质上没有区别。
- 定义pos 代表每个位置上应该填写的数字,每次pos++, 按照转圈的顺序(左上->右上->右下->左下->左上)
代码
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int row_start = 0;
int col_start = 0;
int row_end = n - 1;
int col_end = n - 1;
int pos = 1;
while (pos <= n * n) {
for (int i = row_start, j = col_start; j <= col_end; j++) {
matrix[i][j] = pos++;
}
row_start++;
for (int i = row_start, j = col_end; i <= row_end; i++) {
matrix[i][j] = pos++;
}
col_end--;
if (row_start <= row_end ) { //因为是正方形矩阵,判断行列中的一个即可.
for (int i = row_end, j = col_end; j >= col_start; j--) {
matrix[i][j] = pos++;
}
row_end--;
for (int i = row_end, j = col_start; i >= row_start; i--) {
matrix[i][j] = pos++;
}
col_start++;
}
}
return matrix;
}
}