funcgenerateMatrix(n int) [][]int { ret := make([][]int, n) for i := 0; i < n; i++ { ret[i] = make([]int, n) } total := n * n up, down, left, right := 0, n-1, 0, n-1 for i := 1; i <= total; { for j := left; j <= right; j++ { ret[up][j] = i i++ } for j := up + 1; j <= down; j++ { ret[j][right] = i i++ } if up != down { for j := right - 1; j >= left; j-- { ret[down][j] = i i++ } } if left != right { for j := down - 1; j > up; j-- { ret[j][left] = i i++ } } up++ down-- left++ right-- } return ret }
The key points to resolve LeetCode problem 885. Spiral Matrix III : a. After observing the spiral path, you can get the pattern of the step sequence: 1, 1, 2, 2, 3, 3, 4, 4 b. Figure out a way to make a spiral circle n % 4