# C language force buckle the 59th spiral matrix ②.analog matrix

2022-08-06 07:36:01

59. Spiral Matrix II

Given you a positive integer `n` , generate a `1` to `n2` all elements, and the elements are spirally arranged in clockwise order `n x n` square matrix `matrix` .

Example 1: `Enter:n = 3Output:[[1,2,3],[8,9,4],[7,6,5]]`

Example 2:

`Enter:n = 1Output:[]`

Tip:

• `1 <= n <= 20`

The idea of ​​this topic is similar to that of I. If you are interested, you can refer to another blog of mine.

C language forcefully deducts the spiral matrix of the 54th question.Analog Rotation

Generation of the simulation matrix.As required, the initial position is set to the upper left corner of the matrix, and the initial orientation is set to the right.If the position of the next step is beyond the bounds of the matrix, or is a previously visited position, rotate clockwise to enter the next direction.This is repeated until n^2 elements are filled.

Denote matrix as the generated matrix, whose initial elements are set to 0.Since the filled elements are all positive numbers, we can judge the element value of the current position. If it is not 0, it means that this position has been visited.

Generate an n×n empty matrix mat, and then simulate the entire inward wrapping filling process:

-Define the current left and right upper and lower boundaries l,r,t,b, the initial value num = 1, the iteration termination value tar = n * n;
-When num <= tar, always follow from left to leftFill in the sequence loop from top to bottom, right to left, bottom to top, after each filling:
- Execute num += 1: get the next number to be filled in;
- update the boundary: For example, after filling from left to right, the upper boundary t += 1, which is equivalent to shrinking the upper boundary by 1.
- Using num <= tar instead of l < r || t < b as the iteration condition is to solve the problem that when n is odd, the center number of the matrix cannot be filled during the iteration.

``int** generateMatrix(int ​​n, int* returnSize, int** returnColumnSizes) {int maxNum = n * n;int curNum = 1;int** matrix = malloc(sizeof(int*) * n);*returnSize = n;*returnColumnSizes = malloc(sizeof(int) * n);for (int i = 0; i < n; i++) {matrix[i] = malloc(sizeof(int) * n);memset(matrix[i], 0, sizeof(int) * n);(*returnColumnSizes)[i] = n;}int row = 0, column = 0;int directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // lower right upper leftint directionIndex = 0;while (curNum <= maxNum) {matrix[row][column] = curNum;curNum++;int nextRow = row + directions[directionIndex], nextColumn = column + directions[directionIndex];if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || matrix[nextRow][nextColumn] != 0) {directionIndex = (directionIndex + 1) % 4; // rotate clockwise to the next direction}row = row + directions[directionIndex];column = column + directions[directionIndex];}return matrix;}``