翻译

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

原文

Given an integer n$n$, generate a square matrix filled with elements from 1$1$ to n2$n^2$ in spiral order.

For example,
Given n=3$n = 3$,

You should return the following matrix:

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

代码

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;
}

04-14 47

04-03 101

10-19 1347

06-26 30

07-31 2507

04-29 431

11-28 1163

06-18 253

11-17 4939

每天一道LeetCode-----将m × n矩阵按照顺时针螺旋顺序转化成一维数组

©️2020 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。