mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
这种方法的实现思路和卡尔哥讲的不一样 补充卡尔哥的解题思路方便大家理解
This commit is contained in:
@ -300,6 +300,61 @@ function generateMatrix(n: number): number[][] {
|
|||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
n := 3
|
||||||
|
fmt.Println(generateMatrix(n))
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateMatrix(n int) [][]int {
|
||||||
|
startx, starty := 0, 0
|
||||||
|
var loop int = n / 2
|
||||||
|
var center int = n / 2
|
||||||
|
count := 1
|
||||||
|
offset := 1
|
||||||
|
res := make([][]int, n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
res[i] = make([]int, n)
|
||||||
|
}
|
||||||
|
for loop > 0 {
|
||||||
|
i, j := startx, starty
|
||||||
|
|
||||||
|
//行数不变 列数在变
|
||||||
|
for j = starty; j < n-offset; j++ {
|
||||||
|
res[startx][j] = count
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
//列数不变是j 行数变
|
||||||
|
for i = startx; i < n-offset; i++ {
|
||||||
|
res[i][j] = count
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
//行数不变 i 列数变 j--
|
||||||
|
for ; j > starty; j-- {
|
||||||
|
res[i][j] = count
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
//列不变 行变
|
||||||
|
for ; i > startx; i-- {
|
||||||
|
res[i][j] = count
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
startx++
|
||||||
|
starty++
|
||||||
|
offset++
|
||||||
|
loop--
|
||||||
|
}
|
||||||
|
if n%2 == 1 {
|
||||||
|
res[center][center] = n * n
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func generateMatrix(n int) [][]int {
|
func generateMatrix(n int) [][]int {
|
||||||
top, bottom := 0, n-1
|
top, bottom := 0, n-1
|
||||||
|
Reference in New Issue
Block a user