LeetCode -- Spiral Matrix II
Description:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You shoshould return the following matrix:
[
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]
]
Given a number, the matrix is generated from the external to the internal.
Ideas:
This topic is mainly to complete a rotating process. The width of the track cycle is divided into four different directions: left-to-right, top-to-bottom, right-to-left, and left-to-top. Cycle decreases every time.
Pay attention to the difference in cycle values where n is an odd and even number.
Implementation Code:
public class Solution { public int[,] GenerateMatrix(int n) { var matrix = new int[n,n]; var row = n % 2 == 0 ? n / 2 : (n+1) / 2; var count = 1; for(var cycle = 0;cycle < row; cycle++){ // left to right for(var col = cycle;col < n - cycle - 1; col++){ matrix[cycle,col] = count ++; } // right to bottom for(var r = cycle ; r < n - cycle; r++){ matrix[r, n - cycle - 1] = count ++; } // bottom to left for(var col = n - cycle - 2;col >= cycle; col --){ matrix[n-cycle-1,col] = count ++; } // left to top for(var r = n - cycle - 2;r > cycle; r --){ matrix[r,cycle] = count ++; } } return matrix; }}