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 ]]
此题跟之前那道 本质上没什么区别,就相当于个类似逆运算的过程,这道题是要按螺旋的顺序来填数,由于给定矩形是个正方形,我们计算环数时用n / 2来计算,若n为奇数时,此时最中间的那个点没有被算在环数里,所以最后需要单独赋值,还是下标转换问题是难点,参考之前 的讲解来转换下标吧,代码如下:
class Solution {public: vector> generateMatrix(int n) { vector > res(n, vector (n, 1)); int val = 1, p = n; for (int i = 0; i < n / 2; ++i, p -= 2) { for (int col = i; col < i + p; ++col) res[i][col] = val++; for (int row = i + 1; row < i + p; ++row) res[row][i + p - 1] = val++; for (int col = i + p - 2; col >= i; --col) res[i + p - 1][col] = val++; for (int row = i + p - 2; row > i; --row) res[row][i] = val++; } if (n % 2 != 0) res[n / 2][n / 2] = val; return res; }};
本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。