题解 | #蛇形矩阵#
蛇形矩阵
https://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e
package main import ( "fmt" ) func printMatrix(n int) { matrix := make([][]int, n) for i:=0; i<n; i++ { matrix[i] = make([]int, n) } num := 1 for i:=0; i<n; i++ { row := i for j:=0; j<=i; j++ { matrix[row][j] = num row-- num++ } } for i:=0; i<n; i++ { for j:=0; j<n && matrix[i][j] != 0; j++ { fmt.Printf("%d ", matrix[i][j]) } fmt.Println() } } func main() { var n int fmt.Scan(&n) printMatrix(n) }
// 本题输入为一个数字,所以采用 fmt.Scan(&n)