Topic Link: 59. Spiral Matrix II
zero, description
Given a positive integer n, generate an array containing 1 to n 2 n^2n2 all elements, and the nxn square matrix matrix with elements spirally arranged in clockwise order
Example:
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
1. Solution: Simulation
Simulation matrix generation.
The initial position is set to the upper left corner of the matrix, and the initial direction is set to the right.
If the position of the next step exceeds the boundary of the matrix, or is a previously visited position, rotate clockwise and enter the next direction. Repeat this until n 2 n^2 is filledn2 elements.
Key: logic in circles
- Create a two-dimensional array
vector<vector<int>> res(n,vector<int>(n));
- Clockwise order, first fix the number of rows, from (top, left) to (top, right)
- Then fix the number of columns, from (top+1, right) to (bottom, right) [Note: top needs +1]
- Then fix the number of rows, from (bottom, right-1) to (bottom, left)
- Then fix the number of columns, from (bottom-1, left) to (top+1, left) [Note: At this time, due to the top+1 above, the arrival is top+1 at this time]
- complete a lap
- Note that it is (top+1, left) at this time, not the starting point of the next cycle, but left+1
- The starting point is (top+1, left+1)
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n));
int up = 0, down = n - 1, left = 0, right = n - 1, index = 1;
while(index <= n * n){
for(int i = left; i <= right; i++){
res[up][i] = index++;
}
up++;
for(int i = up; i <= down; i++){
res[i][right] = index++;
}
right--;
for(int i = right; i >= left; i--){
res[down][i] = index++;
}
down--;
for(int i = down; i >= up; i--){
res[i][left] = index++;
}
left++;
}
return res;
}
};