leetcode 上有一个题目,是数组顺时针螺旋输出,本人用Go 语言实现了,通过了测试,
有兴趣的朋友,可以用Python 去实现。
题目来源于leetcode
https://leetcode.com/problems/spiral-matrix/
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
![666756844993879fd74bf3b1bfc0a5ef.png](https://i-blog.csdnimg.cn/blog_migrate/243866c28922730bdc0f711c0668f226.jpeg)
/** 数组螺旋输出,黄哥Go 编程培训 黄哥所写*/package mainimport "fmt"func spiralOrder(matrix [][]int) []int {result := []int{}if len(matrix) == 0 {return result}length := len(matrix)row := lengthcol := len(matrix[0])x, y := 0, 0 // x 开始的行 y 开始的列i := 0for x <= row-1 && y <= col-1 {if y < col {for i = y; i < col; i++ {result = append(result, matrix[x][i])}x++}if x < row {for i = x; i < row; i++ {result = append(result, matrix[i][col-1])}col--}if x < row {for i = col - 1; i >= y; i-- {result = append(result, matrix[row-1][i])}row--}if x < row && y < col {for i = row - 1; i >= x; i-- {result = append(result, matrix[i][y])}y++}}return result}/** 数组螺旋输出,黄哥Go 编程培训 黄哥所写*/func spiralPrint(arr [][]int) {if len(arr) == 0 {return}length := len(arr)row := lengthcol := len(arr[0])// fmt.Println(row, col)x, y := 0, 0 // x 开始的行 y 开始的列i := 0for x <= row-1 && y <= col-1 {if y < col {for i = y; i < col; i++ {fmt.Printf(" %d", arr[x][i])}x++}if x < row {for i = x; i < row; i++ {fmt.Printf(" %d", arr[i][col-1])}col--}if x < row {for i = col - 1; i >= y; i-- {fmt.Printf(" %d", arr[row-1][i])}row--}if x < row && y < col {for i = row - 1; i >= x; i-- {fmt.Printf(" %d", arr[i][y])}y++}}}func main() {arr := [][]int{[]int{1, 2, 3},[]int{4, 5, 6},[]int{7, 8, 9},}spiralPrint(arr)fmt.Println()arr = [][]int{[]int{1, 2, 3, 4},[]int{5, 6, 7, 8},[]int{9, 10, 11, 12},}spiralPrint(arr)fmt.Println()arr = [][]int{[]int{3, 2},// []int{2},}spiralPrint(arr)fmt.Println()arr = [][]int{[]int{2, 5, 8},[]int{4, 0, -1},}spiralPrint(arr)fmt.Println()arr = [][]int{[]int{1},[]int{2},[]int{3},[]int{4},[]int{5},[]int{6},[]int{7},[]int{8},[]int{9},[]int{10},}spiralPrint(arr)fmt.Println()arr = [][]int{[]int{1, 2, 3, 4},[]int{5, 6, 7, 8},[]int{9, 10, 11, 12},[]int{13, 14, 15, 16},}spiralPrint(arr)fmt.Println()}
通过测试
![adcf38ec710ab3e730583c4ea3a8dd20.png](https://i-blog.csdnimg.cn/blog_migrate/47a2a1c0e90577d009bb073b15e3ca66.jpeg)
Go代码中有几个测试用例。
调用 spiralPrint函数输出的结果。
1 2 3 6 9 8 7 4 5
1 2 3 4 8 12 11 10 9 5 6 7
3 2
2 5 8 -1 0 4
1 2 3 4 5 6 7 8 9 10
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10