Topic:
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]]
idea: The problem is the same as the spiral matrix model and solution. We are asked to write the 1~n^2 number into the matrix. We still maintain four variables, Rowbegin, Rowend, Colbegin, Colend. And then to define the boundary of the helix. What we need to note is that if n is 0, we should return an empty array. And when writing numbers, we also need to determine whether the current number exceeds the maximum number of n^2, if exceeded, we do not need to traverse the. And most importantly, when an array is uninitialized, the subscript operator is not allowed to change the array elements, so we must first initialize the array, which is initialized to n rows n columns, and the elements are 0 arrays.
Attention:
1. Return to the empty group and forget the brackets.
if (n = = 0) return vector<vector<int>> ();
2. Initializing an array
vector<vector<int>> ret (n, vector<int> (n, 0));
3. Remember to determine whether the maximum number is reached. Each traversal needs to be judged
if (num <= n^2) { //Right traversal add for (int j = colbegin; J <= Colend; j + +) { Ret[rowbegin][j] = Nu m; num++; } }
Complexity: O (n^2) n is the input number
AC Code:
Class Solution {public:vector<vector<int> > Generatematrix (int n) {if (n = = 0) return Vector<vec Tor<int>> (); vector<vector<int>> ret (n, vector<int> (n, 0)); int rowbegin = 0; int rowend = n-1; int colbegin = 0; int colend = n-1; int num = 1; while (Rowbegin <= rowend && colbegin <= colend) {if (num <= n^2) { Right traversal add for (int j = colbegin; J <= Colend; j + +) {Ret[rowbeg IN][J] = num; num++; }} rowbegin++; if (num <= n^2) {//Traverse down add for (int i = rowbegin; I <= rowend; i++) {Ret[i][colend] = num; num++; }} colend--; if (Num <= n^2) {//Left traversal add for (int j = colend; J >= Colbegin; j--) {ret[rowend][j] = num; num++; }} rowend--; if (num <= n^2) {//Up traversal add for (int i = rowend; I >= rowbegin; i--) {Ret[i][colbegin] = num; num++; }} colbegin++; } return ret; }};
[C + +] leetcode:110 Spiral Matrix II (Spiral write matrix)