给定一个整数 n ,生成一个矩阵,要求以螺旋状将 1 到 n2 的元素填进其中。
例如,给定 n=3 ,
你应该返回以下矩阵:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
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 ]
]
这个上一题非常类似,54题是由外到内的取值,59题则是有由外到内的赋值,条件甚至都不用变。
LeetCode 54 Spiral Matrix(螺旋矩阵)(Array)(*)
C Plus Plus
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > matrix(n, vector<int>(n) );
int u = 0, d = n - 1, l = 0, r = n - 1, k = 0;
while (true) {
// up
for (int col = l; col <= r; col++) matrix[u][col] = ++k;
if (++u > d) break;
// right
for (int row = u; row <= d; row++) matrix[row][r] = ++k;
if (--r < l) break;
// down
for (int col = r; col >= l; col--) matrix[d][col] = ++k;
if (--d < u) break;
// left
for (int row = d; row >= u; row--) matrix[row][l] = ++k;
if (++l > r) break;
}
return matrix;
}
};
Java
updated at 2016/09/04
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
if (n < 1) return matrix;
int u = 0, d = n - 1, l = 0, r = n - 1, k = 1;
while (true) {
// up
for (int col = l; col <= r; col++) matrix[u][col] = k++;
if (++u > d) break;
// right
for (int row = u; row <= d; row++) matrix[row][r] = k++;
if (--r < l) break;
// down
for (int col = r; col >= l; col--) matrix[d][col] = k++;
if (--d < u) break;
// left
for (int row = d; row >= u; row--) matrix[row][l] = k++;
if (++l > r) break;
}
return matrix;
}